⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 autoclosedlg.cpp

📁 一个用VC++写的定时关机的小程序的源代码
💻 CPP
字号:
// AutoCloseDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AutoClose.h"
#include "AutoCloseDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAutoCloseDlg dialog

CAutoCloseDlg::CAutoCloseDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAutoCloseDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAutoCloseDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAutoCloseDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAutoCloseDlg)
		
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAutoCloseDlg, CDialog)
	//{{AFX_MSG_MAP(CAutoCloseDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_CBN_SELCHANGE(IDC_HOUR, OnSelchangeHour)
	ON_CBN_SELCHANGE(IDC_MIN, OnSelchangeMin)
	ON_BN_CLICKED(IDC_BUTTON2, OnStart)
	ON_WM_DESTROY()
	ON_COMMAND(ID_ABOUT, OnAbout)
	ON_COMMAND(ID_STOP, OnStop)
	ON_COMMAND(ID_DISPLAY, OnDisplay)
	ON_COMMAND(ID_QUIT, OnQuit)
	ON_WM_LBUTTONDOWN()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAutoCloseDlg message handlers

BOOL CAutoCloseDlg::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 dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	SetWindowPos(&CWnd::wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
	CenterWindow(GetDesktopWindow());    //让窗口处于屏幕中间
	SetWindowText("MFC自动关机程序!");
    SetTimer(10,100,NULL);              //调用OnTimer函数,并使之没隔一秒发送一次 WM_TIMER 消息
    CComboBox *hour;
	CComboBox *min;
	hour=(CComboBox*)GetDlgItem(IDC_HOUR);
	min=(CComboBox*)GetDlgItem(IDC_MIN);

	////////////添加24小时///////////////////
	for(int i=0;i<=23;i++)         
	{
		if(i<10)
		{
		    CString s;
		    s.Format("0%d",i);
			hour->AddString(s);
		}
		else
		{
			CString ss;
			ss.Format("%d",i);
		    hour->AddString(ss);
		}
	}
    /////////////添加60分钟////////////////
	for(i=0;i<=59;i++)
	{
		if(i<10)
		{
		    CString s;
		    s.Format("0%d",i);
			min->AddString(s);
		}
		else
		{
			CString ss;
			ss.Format("%d",i);
		    min->AddString(ss);
		}
	}
return TRUE;  // return TRUE  unless you set the focus to a control
}

void CAutoCloseDlg::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 CAutoCloseDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int 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 icon
		dc.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 CAutoCloseDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CAutoCloseDlg::OnTimer(UINT nIDEvent) 
{
	CTime t=CTime::GetCurrentTime();   //取出当前时间
    int y=t.GetYear();
	int d=t.GetDay();
	int m=t.GetMonth();
	int h=t.GetHour();
	int min=t.GetMinute();
	int s=t.GetSecond();

	CString yy,dd,mm,hh,mins,ss,total;
	yy.Format("%d",y);
	dd.Format("%d",d);
	mm.Format("%d",m);
	if(h<10)
	    hh.Format("0%d",h);
	else
		hh.Format("%d",h);
	if(min<10)
        mins.Format("0%d",min);
	else
	    mins.Format("%d",min);
	if(s<10)
	    ss.Format("0%d",s);
	else
		ss.Format("%d",s);

    total=yy+"-"+mm+"-"+dd+"  "+hh+":"+mins+":"+ss;

	CStatic *displaytime;
	displaytime=(CStatic*)GetDlgItem(IDC_STATIC);
	displaytime->SetWindowText(total);                     //在静态文本框中显示出当前时间

	/////////////////准备关机//////////////////////
	if(begin && close_hour.CompareNoCase(hh)==0 && close_min.CompareNoCase(mins)==0)
	{
		KillTimer(10);
		
        if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
		{
		    MessageBox("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) 
		{
            MessageBox("AdjustTokenPrivileges enable failed!");
		}

	    fResult =InitiateSystemShutdown( 
             NULL,                                  // 要关的计算机用户名
             "由于系统不稳定,WINDOWS将在上面的时间内关机,请做好保存工作!",  // 显示的消息
             10,                                    // 关机所需的时间
             TRUE,                                  
             TRUE);                               //设为TRUE为重起,设为FALSE为关机
	    if(!fResult) 
		{ 
             MessageBox("InitiateSystemShutdown failed."); 
		} 

	    tkp.Privileges[0].Attributes = 0; 
        AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); 

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

	    ExitWindowsEx(EWX_SHUTDOWN,0);
	}
    CDialog::OnTimer(nIDEvent);
}

void CAutoCloseDlg::OnSelchangeHour() 
{
    CComboBox *hour;
	hour=(CComboBox*)GetDlgItem(IDC_HOUR);
	hour->GetWindowText(close_hour);        
}

void CAutoCloseDlg::OnSelchangeMin() 
{
	CComboBox *min;
	min=(CComboBox*)GetDlgItem(IDC_MIN);
	min->GetWindowText(close_min);	
}
//////////////取出 Combo Box 中的值////////////////////

void CAutoCloseDlg::OnStart() 
{
    begin=true;
    ShowWindow(SW_HIDE);
//////////////////定义系统托盘///////////////////////////
	m_tnid.cbSize=sizeof(NOTIFYICONDATA);//设置结构大小//
	m_tnid.hWnd=this->m_hWnd;//设置图标对应的窗口
    m_tnid.uFlags=NIF_MESSAGE|NIF_ICON|NIF_TIP;//图标属性
    m_tnid.uCallbackMessage=MYWM_NOTIFYICON;//应用程序定义的回调消息ID
////////////设置NOTIFYICONDATA结构///////////
	CString szToolTip;
    szToolTip=_T("MFC自动关机程序");
    _tcscpy(m_tnid.szTip, szToolTip);//帮助信息
    m_tnid.uID=IDR_MAINFRAME;//应用程序图标
    HICON hIcon;
    hIcon=AfxGetApp()->LoadIcon(IDR_MAINFRAME);
    m_tnid.hIcon=hIcon;//图标句柄
	PNOTIFYICONDATA m_ptnid=&m_tnid;
	::Shell_NotifyIcon(NIM_ADD,m_ptnid);//增加图标到系统盘
    if(hIcon)::DestroyIcon(hIcon);
//////////////////定义系统托盘///////////////////////////
}
///////////////////处理系统托盘的消息///////////////////////
LRESULT CAutoCloseDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	switch(message)
	{
        case MYWM_NOTIFYICON:
    //如果是用户定义的消息
        if(lParam==WM_LBUTTONDBLCLK)
		{
        //鼠标双击时主窗口出现
		    AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOW);
		}
        else if(lParam==WM_RBUTTONDOWN)    //鼠标右键单击弹出选单
		{ 
            CMenu menu;
            menu.LoadMenu(IDR_MENU1); //载入事先定义的选单
            CMenu *pMenu=menu.GetSubMenu(0);
            CPoint pos;
	        GetCursorPos(&pos);
            pMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,pos.x,pos.y,AfxGetMainWnd());
		}
        break;
        case WM_SYSCOMMAND:
        //如果是系统消息
        if(wParam==SC_MINIMIZE)
		{
            //接收到最小化消息时主窗口隐藏
            AfxGetApp()->m_pMainWnd->ShowWindow(SW_HIDE);
            return 0;
		}
        break;
	}
	return CDialog::WindowProc(message, wParam, lParam);
}
///////////////////处理系统托盘的消息///////////////////////

void CAutoCloseDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	::Shell_NotifyIcon(NIM_DELETE,&m_tnid);
}

void CAutoCloseDlg::OnAbout() 
{
	MessageBox("自动关机程序");	
}

void CAutoCloseDlg::OnStop() 
{
	begin=false;
	ShowWindow(1);
	::Shell_NotifyIcon(NIM_DELETE,&m_tnid);
}

void CAutoCloseDlg::OnDisplay() 
{
	ShowWindow(1);
	::Shell_NotifyIcon(NIM_DELETE,&m_tnid);
}

void CAutoCloseDlg::OnQuit() 
{
	PostQuitMessage(0);
}

void CAutoCloseDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
    CDialog::OnLButtonDown(nFlags, point); 
    // 发送WM_NCLBUTTONDOWN消息 
    // 使Windows认为鼠标在标题条上 
    PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(point.x, point.y)); 	
	CDialog::OnLButtonDown(nFlags, point);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -