수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1695004
  • Today | 749
  • Yesterday | 606

Programming/MFC2007/03/25 00:30

윈도우 종류 및 종료하기

윈도우 종류 알아내기

CString CWindowCloserDlg::GetWindows()
{
   //////////////////////////////
   // OS detection routine.

   OSVERSIONINFO version;
   version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

   CString bNT;

   if(GetVersionEx(&version))
   {
       DWORD dwplatformid = version.dwPlatformId;
       switch (version.dwPlatformId)
       {
       case VER_PLATFORM_WIN32s:
       // strplatformid.Format("Windows 3.1");
           bNT = "Windows 3.1";
           break;
       case VER_PLATFORM_WIN32_WINDOWS:
           if(version.dwMinorVersion == 0)
           {
           //    strplatformid.Format("Windows 95");
               bNT = "Windows 95";
           }            
           else if(version.dwMinorVersion == 10)
           {
           //    strplatformid.Format("Windows 98");
               bNT = "Windows 98";
           }
           else
           {
               bNT = "Windows Me";
           }
           break;
       case VER_PLATFORM_WIN32_NT:
       // strplatformid.Format("Windows NT");
           if (version.dwMinorVersion == 0 && version.dwMajorVersion == 4 )
           {
               bNT = "Windows NT 4.0";
           }
           else if (version.dwMinorVersion == 0 && version.dwMajorVersion == 5)
           {
               bNT = "Windows 2000";
           }
           else if (version.dwMinorVersion == 1)
           {
               bNT = "Windows XP";
           }
           else if (version.dwMinorVersion == 2)
           {
               bNT = "Windows Server 2003";
           }
           else
           {
               bNT = "Windows NT 3.51";
           }            
           break;
       default:
           bNT = "UnKnown";
           break;
       }
   }
   return bNT;

}


윈도우 95, 98, ME

void CShutdown::SetShutDownMode(UINT l_bMode)
{
   if(l_bMode == LOGOFF)
       OnWindowsLogOff();
   else if(l_bMode == REBOOT)
       SystemShutdown(TRUE);
   else if(l_bMode == SHUTDOWN)
       SystemShutdown(FALSE);
}

BOOL CShutdown::SystemShutdown(BOOL l_bReboot)
{
   if(GetWindowsSystemType())     // If This OS is like WinNT, The Return value is TRUE
   {
       HANDLE hToken;             // handle to process token
       TOKEN_PRIVILEGES tkp;     // pointer to token structure

       CString l_sErrorCode;

       if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
           AfxMessageBox("OpenProcessToken failed.");

       LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
       tkp.PrivilegeCount = 1;
       tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
       AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

       if (GetLastError() != ERROR_SUCCESS)
           AfxMessageBox("AdjustTokenPrivileges enable failed.");

       if(!InitiateSystemShutdown(    NULL,
                       NULL,    //"System Shutdown , so You must Save datas of Each Application ",
                       0,
                       TRUE,
                       l_bReboot))        //<--이 함수가 2번째 Argument에 NULL을 입력해도 NT에서만 메세지가 나타나는지 검사할것.
       {                            //또다른 함수로써 ExitWindowsEx가 있음 이 함수의 Flag로써는 종료시 EWX_SHUTDOWN을 이용하면 됨
           l_sErrorCode.Format("%d",GetLastError());
           if(l_sErrorCode != "1115")
           {
               AfxMessageBox("Abort System Shutdown! Error Code is "+l_sErrorCode);
               return FALSE;
           }
       }

       return TRUE;
   }
   else
   {
       if(l_bReboot)
           return ExitWindowsEx(EWX_REBOOT,0);
       else
           return ExitWindowsEx(EWX_SHUTDOWN,0);
   }
}

BOOL CShutdown::OnWindowsLogOff()
{
   return ExitWindowsEx(EWX_LOGOFF,0);
}

BOOL CShutdown::GetWindowsSystemType()
{
   UINT l_uiVersion = GetVersion();

   if (l_uiVersion < 0x80000000)             // Windows NT
       return TRUE;
   else
       return FALSE;
}


윈도우 NT 계열

BOOL InitiateSystemShutdown
(
   LPTSTR lpMachineName,        // pointer to name of computer to shut down
   LPTSTR lpMessage,            // pointer to message to display in dialog box
   DWORD dwTimeout,            // time to display dialog box
   BOOL bForceAppsClosed,        // force applications closed flag
   BOOL bRebootAfterShutdown    // reboot flag
);

void ShutDownNT()
{
   HANDLE hToken;             // handle to process token
   TOKEN_PRIVILEGES tkp;     // pointer to token structure

   BOOL fResult;             // system shutdown flag

   // Get the current process token handle so we can get shutdown
   // privilege.
   if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
       AfxMessageBox("OpenProcessToken failed.");

   // Get the LUID for shutdown privilege.
   LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

   tkp.PrivilegeCount = 1; // one privilege to set
   tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

   // Get shutdown privilege for this process.
   AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

   // Cannot test the return value of AdjustTokenPrivileges.
   if (GetLastError() != ERROR_SUCCESS)
       AfxMessageBox("AdjustTokenPrivileges enable failed.");

   // Display the shutdown dialog box and start the time-out countdown.

   fResult = InitiateSystemShutdown(
               NULL,                    // shut down local computer
               "System rebooting.",    // message to user
               0,                     // time-out period (<- 여기를 20 이라고 쓰면 20초 후                에 리부팅한다.)
               FALSE,                    // ask user to close apps
               TRUE);                    // reboot after shutdown

   if (!fResult)
   {
       AfxMessageBox("InitiateSystemShutdown failed.");
   }

   // error string..
   //PrintCSBackupAPIErrorMessage(GetLastError());
   // Disable shutdown privilege.
   tkp.Privileges[0].Attributes = 0;
   AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

   if (GetLastError() != ERROR_SUCCESS)
   {
       AfxMessageBox("AdjustTokenPrivileges disable failed.");
   }
}

이제 OS 가 win NT 계열인지 알아내는 function 이 필요하다. win 2000 도 NT 기반이다.

BOOL IsOsNT()
{
   //////////////////////////////
   // OS detection routine.

   OSVERSIONINFO version;
   /* First we have to find out which OS we are running on */
   version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
   /* If we get and error, we can"t continue. */

   // CString strplatformid;
   BOOL bNT = FALSE;

   if(GetVersionEx(&version))
   {
       DWORD dwplatformid = version.dwPlatformId;
       switch (version.dwPlatformId)
       {
       case VER_PLATFORM_WIN32s:
           // strplatformid.Format("Windows 3.1");
           bNT = FALSE;
           break;
       case VER_PLATFORM_WIN32_WINDOWS:
           if(version.dwMinorVersion == 0)
           {
               //    strplatformid.Format("Windows 95");
               bNT = FALSE;
           }
           else if(version.dwMinorVersion > 0)
           {
               //    strplatformid.Format("Windows 98");
               bNT = FALSE;
           }
           break;
       case VER_PLATFORM_WIN32_NT:
           // strplatformid.Format("Windows NT");
           bNT = TRUE;
           break;
       default:
           bNT = FALSE;
           break;
       }
   }

   return bNT;
}

리부팅하려면 메시지 창을 하나 보여주고 다음과 같이 OS 에 따라 적절한 function 을 call 해준다.


int nResult = ::MessageBox(NULL,
   "새로운 설정 내용을 적용하기위해 시스템을 다시 시작합니다.",
   "시스템 설정 바꾸기",
   MB_OK);

if(nResult == IDOK)
{
   if(IsOsNT())
   {
       ShutDownNT(); //NT,2000
   }
   else
   {
       ExitWindowsEx( EWX_REBOOT, 0 ); //win95,98,ME
   }
}
"MFC" 카테고리의 다른 글
  • 프로그램내에서 한영전환 하기 ImmGetConversionSt... (0)2007/03/26
  • 프로그램 중복 실행 방지 (0)2007/03/26
  • 윈도우 종류 및 종료하기 (0)2007/03/25
  • 툴바의 툴팁을 내가 원하는데로 (0)2007/03/23
  • Child윈도를 Popup시키는 방법 (0)2007/03/23
2007/03/25 00:30 2007/03/25 00:30
Posted by webdizen
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/2747

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1 ... 502 503 504 505 506 507 508 509 510 ... 3009  Next»

RSS HanRSS
Blog Image
webdizen
이곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (3009)
Webdizen (141)
Life (6)
Diary (16)
Blog (9)
IDEA (2)
Travel (10)
Book (16)
Photo (7)
Movie (8)
Music (14)
Leisure Sports (10)
Funny (6)
Hardware (121)
Software (120)
Windows (5)
Unix & Linux (120)
Installation (5)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (804)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (2)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (4)
Network (66)
Web (79)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • 스냅샷 격리
  • w3m
  • 한서관
  • PNG
  • Dropdown
  • Web Services
  • FoxPro
  • CodeIgniter
  • HyperBac
  • 노틀담
  • 신발
  • 로그
  • 원격 네트워크
  • Connection String
  • Qrobo
  • Collection
  • 콘텐츠
  • 쓰레드
  • Goowy
  • 감정이입

Recent Articles

  • 트위터(Twitter)의 시작!.
  • 청년 리더의 조건.
  • 애플의 타블렛 PC - 아이패드....
  • 미래의 인터페이스 - 육감 기....
  • 기초발성법 동영상 강좌.

Recent Comments

  • 경청... 너무나 중요한데.......
    webdizen 14:59
  • 학교 과제물중 쓰레드에 대하....
    장진혁 03/17
  • 관리자만 볼 수 있는 댓글입....
    비밀방문자 03/12
  • 상대방의 이야기를 열심히 경....
    DoNuts 03/03
  • 좋은글 잘 보고 갑니다..
    Und_hacker 01/08

Recent Trackbacks

  • printf,scanf를 이용한 형식....
    yundream의 프로그래밍 이야기 03/10
  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 2009
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007

Archive

  • 2010/02 (1)
  • 2010/01 (6)
  • 2009/12 (5)
  • 2009/09 (3)
  • 2009/08 (1)

Calendar

«   2010/03   »
일 월 화 수 목 금 토
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Polarux - Linuxing
      • Rodman®
      • 까만 나비
      • 나를 가꾸는 시간.
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.