回忆写MFC的青葱岁月——MFC自动关机小程序

来源:互联网 发布:付费wlan和手机网络 编辑:程序博客网 时间:2024/04/27 16:41

今天整理之前的代码突然发现了之前写的一个小程序。记录一下吧,万一哪天硬盘不小心坏了,就找不到了!!

也想起那时候刚接触编程,幼稚的将VC++ 认为是C++,哈哈~~

先上界面

主要支持两种模式:

           精确关机,24小时制式的。

           倒计时关机,分钟制式的。

 先申请关机权限————计时Timer——调用系统调用——最后一分钟每四秒给出提示。

其实在各种电脑卫士里面都有这个功能。

1 上图对话框继承CDialog。

    主要是变量和控件动作的定义。

     

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CAutoshutdownDlg dialogclass CAutoshutdownDlg : public CDialog{// Constructionpublic:bool m_hhmmss;int m_jishi;bool m_isbegin;int m_hour;int m_mminute;int m_minute;int m_jishifen;int flag;int flag1;CAutoshutdownDlg(CWnd* pParent = NULL);// standard constructor// Dialog Data//{{AFX_DATA(CAutoshutdownDlg)enum { IDD = IDD_AUTOSHUTDOWN_DIALOG };CStringm_mm;CStringm_fen;   CStringm_stat;CStringm_sys_time;CStringm_hh;//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAutoshutdownDlg)protected:virtual void DoDataExchange(CDataExchange* pDX);// DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CAutoshutdownDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void Onshutdown();virtual void OnCancel();afx_msg void OnTimer(UINT nIDEvent);afx_msg void OnRadio2();afx_msg void OnRadio1();afx_msg void OnDropdownCombo1();afx_msg void OnDropdownCombo2();afx_msg void OnDropdownCombo3();afx_msg void OnButton1();//}}AFX_MSGDECLARE_MESSAGE_MAP()};



2 看具体对话框实现。MFC把很多实现封装的很完整。仅做一些我们的消息处理逻辑即可。


/////////////////////////////////////////////////////////////////////////////// CAutoshutdownDlg dialogCAutoshutdownDlg::CAutoshutdownDlg(CWnd* pParent /*=NULL*/): CDialog(CAutoshutdownDlg::IDD, pParent){//初始化时间字段m_mm =_T("");m_fen =_T("");m_stat =_T("");m_sys_time = _T("");        m_jishi=0; m_hh = _T("");//加载图标// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CAutoshutdownDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAutoshutdownDlg)DDX_CBString(pDX, IDC_COMBO2, m_mm);DDX_CBString(pDX, IDC_COMBO3, m_fen);DDX_Text(pDX, IDC_stat, m_stat);DDX_Text(pDX, IDC_sys_time, m_sys_time);DDX_CBString(pDX, IDC_COMBO1, m_hh);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CAutoshutdownDlg, CDialog)//{{AFX_MSG_MAP(CAutoshutdownDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(ID_shutdown, Onshutdown)ON_WM_TIMER()ON_BN_CLICKED(IDC_RADIO2, OnRadio2)ON_BN_CLICKED(IDC_RADIO1, OnRadio1)ON_CBN_DROPDOWN(IDC_COMBO1, OnDropdownCombo1)ON_CBN_DROPDOWN(IDC_COMBO2, OnDropdownCombo2)ON_CBN_DROPDOWN(IDC_COMBO3, OnDropdownCombo3)ON_BN_CLICKED(IDC_BUTTON1, OnButton1)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CAutoshutdownDlg message handlersBOOL CAutoshutdownDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog.  The framework does this automatically//  when the application's main window is not a dialogSetIcon(m_hIcon, TRUE);// Set big iconSetIcon(m_hIcon, FALSE);// Set small icon// TODO: Add extra initialization here//=====================================================================================    //使此进程获取:关机权限              HANDLE hToken;              LUID luid;              TOKEN_PRIVILEGES tp;              //获取此进程的令牌           ::OpenProcessToken(::GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);             /查询权限值:获取权限的唯一标识值          ::LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&luid);             tp.PrivilegeCount = 1;             tp.Privileges[0].Luid = luid;          tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;             //调整令牌权限          ::AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),NULL,NULL);             //=====================================================================================         //init cstring==========================================================================      /*  m_hh.Format("NULL");m_mm.Format("NULL");m_fen.Format("NULL");*///set timer (show sys_time)=============================================================    ::SetTimer(m_hWnd,1,1000,NULL);//set m_stat============================================================================    CWnd *pWnd1= GetDlgItem(IDC_COMBO1);CWnd *pWnd2= GetDlgItem(IDC_COMBO2);CWnd *pWnd3= GetDlgItem(IDC_COMBO3);CWnd *pWnd4= GetDlgItem(IDC_stat);pWnd1->EnableWindow(false);pWnd2->EnableWindow(false);pWnd3->EnableWindow(false);pWnd4->SetWindowText("还未开启关机进程");return TRUE;  // return TRUE  unless you set the focus to a control}void CAutoshutdownDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below//  to draw the icon.  For MFC applications using the document/view model,//  this is automatically done for you by the framework.void CAutoshutdownDlg::OnPaint() {if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this to obtain the cursor to display while the user drags//  the minimized window.HCURSOR CAutoshutdownDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}void CAutoshutdownDlg::Onshutdown() {// TODO: Add your control notification handler code here     m_jishi=0; flag=0; flag1=1; UpdateData();     GetDlgItem(IDC_COMBO3)->GetWindowText(m_fen);GetDlgItem(IDC_COMBO2)->GetWindowText(m_mm);GetDlgItem(IDC_COMBO1)->GetWindowText(m_hh);     m_minute=atoi(m_fen);                  CWnd *pWndsy= GetDlgItem(IDC_shengyu);              pWndsy->SetWindowText("倒计时开始...");    if(m_mm==""&&m_hh==""&&m_fen=="")          MessageBox("还没设置偶~(*^_^*)","提示:",MB_OK);else{if( m_hhmmss && (m_mm==""||m_hh==""))         MessageBox("额。没设置全,少分或小时(*^_^*)","提示:",MB_OK);else {if(m_hhmmss==true){              CWnd *pWnd4= GetDlgItem(IDC_stat);              pWnd4->SetWindowText("精确关机进行中...");}if(m_hhmmss==false){              CWnd *pWnd4= GetDlgItem(IDC_stat);              pWnd4->SetWindowText("倒计分关机进行中...");}     ::SetTimer(m_hWnd,2,1000,NULL);         m_isbegin=true;    CWnd *pWnd1= GetDlgItem(IDC_COMBO1);CWnd *pWnd2= GetDlgItem(IDC_COMBO2);CWnd *pWnd3= GetDlgItem(IDC_COMBO3);CWnd *pWnd4= GetDlgItem(IDC_RADIO1);CWnd *pWnd5= GetDlgItem(IDC_RADIO2);pWnd1->EnableWindow(false);pWnd2->EnableWindow(false);pWnd3->EnableWindow(false);pWnd4->EnableWindow(false);pWnd5->EnableWindow(false);}}}void CAutoshutdownDlg::OnCancel() {// TODO: Add extra cleanup here    CDialog::OnCancel();}void CAutoshutdownDlg::OnTimer(UINT nIDEvent) {// TODO: Add your message handler code here and/or call defaultSYSTEMTIME     st;     char     time[30];::GetLocalTime(&st); if(nIDEvent==1){                ::wsprintf(time, "   %d-%d-%d   ",st.wYear,st.wMonth,st.wDay);        ::GetTimeFormat(NULL,TIME_FORCE24HOURFORMAT,&st, "HH ': 'mm ': 'ss ",time,50);          GetDlgItem(IDC_sys_time)->SetWindowText(time);    }        //============================================================================================if(nIDEvent==2){if(m_hhmmss){            m_hour=atoi(m_hh);m_mminute=atoi(m_mm);           if(m_isbegin && m_hour==st.wHour && m_mminute==st.wMinute)                 //当关机标志为开并且当自动关机时间到了               {                  ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE,0);                               //调用ExitWindowsEx关闭机器。                 MessageBox("正在调用关机进程...","提示:",MB_OK);               PostQuitMessage(0);    }    if(m_hour==st.wHour){                  int i=st.wMinute;          int j=m_mminute;  int h=j-i;  if(h<=5){                  CString stl;      stl.Format("%d",h);                  CWnd *pWndsy= GetDlgItem(IDC_shengyu);              pWndsy->SetWindowText("准备关机了,离关机还有"+stl+"分。");  if(h==5)  if(flag==0){  flag=1;                  MessageBox("准备关机了,离关机还有"+stl+"分。离关机还有一分时会给每四秒一响的滴滴声。","提示:",MB_OK);    }  }  if(h<=1)  {  if(flag1%4==0)  Beep(1000,160);  flag1++;  }   }}               if(!m_hhmmss){    m_jishi++;   m_jishifen=m_jishi/60;                                if(m_isbegin && (m_jishifen>=m_minute))                              //当关机标志为开并且当自动关机时间到了               {                ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE,0);                            //调用ExitWindowsEx关闭机器。             MessageBox("正在调用关机进程...","提示:",MB_OK);              PostQuitMessage(0);             }            CWnd *pWndsy= GetDlgItem(IDC_shengyu);    m_jishifen=m_minute*60-m_jishi;            CString stt;stt.Format("%d",m_jishifen);        pWndsy->SetWindowText("离关机还有"+stt+"秒");            if(m_jishifen<=30) Beep(1000,160);    }}//==============================================================================================CDialog::OnTimer(nIDEvent);}void CAutoshutdownDlg::OnRadio1() {// TODO: Add your control notification handler code herem_hhmmss=true;    CWnd *pWnd3= GetDlgItem(IDC_COMBO3);pWnd3->EnableWindow(false);    CWnd *pWnd1= GetDlgItem(IDC_COMBO1);CWnd *pWnd2= GetDlgItem(IDC_COMBO2);CWnd *pWnd4= GetDlgItem(IDC_stat);pWnd1->EnableWindow(true);pWnd2->EnableWindow(true); m_fen.Format("");UpdateData(false);pWnd4->SetWindowText("已选精确关机模式,请输入");}void CAutoshutdownDlg::OnRadio2() {// TODO: Add your control notification handler code herem_hhmmss=false;CWnd *pWnd1= GetDlgItem(IDC_COMBO1);CWnd *pWnd2= GetDlgItem(IDC_COMBO2);CWnd *pWnd3= GetDlgItem(IDC_COMBO3);CWnd *pWnd4= GetDlgItem(IDC_stat);pWnd1->EnableWindow(false);pWnd2->EnableWindow(false);pWnd3->EnableWindow(true); m_hh.Format("");m_mm.Format("");UpdateData(false);pWnd4->SetWindowText("已选倒计分关机模式,请输入");}void CAutoshutdownDlg::OnDropdownCombo1() {// TODO: Add your control notification handler code hereUpdateData();}void CAutoshutdownDlg::OnDropdownCombo2() {// TODO: Add your control notification handler code hereUpdateData();}void CAutoshutdownDlg::OnDropdownCombo3() {// TODO: Add your control notification handler code hereUpdateData();m_minute=atoi(m_fen);           }void CAutoshutdownDlg::OnButton1() {// TODO: Add your control notification handler code here    m_jishi=0;    m_hh.Format("");m_mm.Format("");m_fen.Format("");UpdateData(false);if(m_isbegin==true){KillTimer(2);    MessageBox("已取消关机(*^_^*)","提示:",MB_OK);m_isbegin=false;}else  MessageBox("阿偶~关机进程似乎还没创建(*^_^*)","提示:",MB_OK);    CWnd *pWnd1= GetDlgItem(IDC_COMBO1);CWnd *pWnd2= GetDlgItem(IDC_COMBO2);CWnd *pWnd3= GetDlgItem(IDC_COMBO3);CWnd *pWnd4= GetDlgItem(IDC_RADIO1);CWnd *pWnd5= GetDlgItem(IDC_RADIO2);pWnd1->EnableWindow();pWnd2->EnableWindow();pWnd3->EnableWindow();pWnd4->EnableWindow();pWnd5->EnableWindow();CWnd *pWnd6= GetDlgItem(IDC_stat);pWnd6->SetWindowText("还未开启关机进程");CWnd *pWndsy= GetDlgItem(IDC_shengyu);          pWndsy->SetWindowText("等待关机设置中...");}

3 代码

点击打开下载