求关机、重启、注销代码
如题
[解决办法]
重启使用WMI,网上代码很多。
估计注销也可以使用WMI。
关机使用调用API的类如下:
using System;
using System.Runtime.InteropServices ;
namespace OffComputer
{
/// <summary>
/// Offcomputer 的摘要说明。
/// 关闭计算机
/// </summary>
public class Offcomputer
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport( "kernel32.dll ", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport( "advapi32.dll ", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport( "user32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool ExitWindowsEx(int flg, int rea);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege ";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
public Offcomputer()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static void ShutDown(int i) //i=0 ShutDown i=1 Reboot
{
if (i == 0)
{
DoExitWin(EWX_SHUTDOWN + EWX_FORCE);
}
else if (i == 1)
{
DoExitWin(EWX_REBOOT + EWX_FORCE);
}
}
private static void DoExitWin(int flg)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
}
}
}
[解决办法]
// AutoShutDownDlg.cpp : 实现文件
//
#include "stdafx.h "
#include "AutoShutDown.h "
#include "AutoShutDownDlg.h "
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define WM_TRAYMESSAGE WM_USER+10000;
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CAutoShutDownDlg 对话框
CAutoShutDownDlg::CAutoShutDownDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAutoShutDownDlg::IDD, pParent)
, m_Radio(0)
{
m_NowTime = _T( " ");
m_ShutTime = CTime::GetCurrentTime();
m_IsRun = false;
m_IsShow = true;
m_hIcon = AfxGetApp()-> LoadIcon(IDR_MAINFRAME);
}
void CAutoShutDownDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX,IDC_STATIC_NOW,m_NowTime);
DDX_DateTimeCtrl(pDX,IDC_SHUT_TIME,m_ShutTime);
DDX_Radio(pDX,IDC_RADIO1,m_Radio);
}
BEGIN_MESSAGE_MAP(CAutoShutDownDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_TIMER()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_START, &CAutoShutDownDlg::OnBnClickedStart)
ON_BN_CLICKED(IDC_STOP, &CAutoShutDownDlg::OnBnClickedStop)
ON_NOTIFY(DTN_DATETIMECHANGE, IDC_SHUT_TIME, &CAutoShutDownDlg::OnDtnDatetimechangeShutTime)
ON_BN_CLICKED(IDC_RADIO1, &CAutoShutDownDlg::OnBnClickedRadio1)
ON_BN_CLICKED(IDC_RADIO2, &CAutoShutDownDlg::OnBnClickedRadio2)
ON_BN_CLICKED(IDC_RADIO3, &CAutoShutDownDlg::OnBnClickedRadio3)
ON_BN_CLICKED(IDC_HIDE, &CAutoShutDownDlg::OnBnClickedHide)
END_MESSAGE_MAP()
// CAutoShutDownDlg 消息处理程序
BOOL CAutoShutDownDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
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);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE);// 设置大图标
SetIcon(m_hIcon, FALSE);// 设置小图标
// TODO: 在此添加额外的初始化代码
// 设置个定时器
SetTimer(1,1000,NULL);
//搞个托盘
//NOTIFYICONDATA nid;
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
nid.hIcon = m_hIcon;
nid.uCallbackMessage = WM_TRAYMESSAGE;
nid.hWnd = m_hWnd;
_tcscpy(nid.szTip,L "定时关机 By Red_angelX ");
nid.uID = IDR_MAINFRAME;
Shell_NotifyIcon(NIM_ADD, &nid);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CAutoShutDownDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CAutoShutDownDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast <WPARAM> (dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
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;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR CAutoShutDownDlg::OnQueryDragIcon()
{
return static_cast <HCURSOR> (m_hIcon);
}
LRESULT CAutoShutDownDlg::DefWindowProcW(UINT message,WPARAM wParam,LPARAM lParam)
{
switch(message)
{
case WM_SYSCOMMAND:
if(wParam==SC_MINIMIZE)
{
//CDialog::OnSysCommand(wParam,lParam);
//AfxGetMainWnd()-> ShowWindow(SW_HIDE);
}
break;
case WM_USER+10000:
{
if(lParam == WM_LBUTTONDBLCLK)
{
if(m_IsShow == false)
{
ShowWindow(SW_SHOW);
m_IsShow = true;
}
else
{
ShowWindow(SW_HIDE);
m_IsShow = false;
}
}
}
break;
}
return CDialog::DefWindowProcW(message,wParam,lParam);
}
void CAutoShutDownDlg::OnTimer(UINT nIDEvent)
{
CDialog::OnTimer(nIDEvent);
CTime nowtime = CTime::GetCurrentTime();
m_NowTime = nowtime.Format(_T( "%Y-%m-%d %H:%M:%S "));
UpdateData(false);
if(m_IsRun == true)
{
if(CTime::GetCurrentTime() > = m_ShutTime)
{
ShutDown();
}
}
}
void CAutoShutDownDlg::OnBnClickedStart()
{
// TODO: 在此添加控件通知处理程序代码
m_StartTime = CTime::GetCurrentTime();
GetDlgItem(IDC_START)-> EnableWindow(false);
m_IsRun = true;
}
void CAutoShutDownDlg::OnBnClickedStop()
{
// TODO: 在此添加控件通知处理程序代码
GetDlgItem(IDC_START)-> EnableWindow(true);
m_IsRun = false;
}
bool CAutoShutDownDlg::ShutDown()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return false;
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)
return false;
switch(m_Radio)
{
case 0:
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0))
return false;
break;
case 1:
if(!ExitWindowsEx(EWX_REBOOT | EWX_FORCE,0))
return false;
break;
case 2:
if(!ExitWindowsEx(EWX_LOGOFF | EWX_FORCE,0))
return false;
break;
}
return true;
}
void CAutoShutDownDlg::OnDtnDatetimechangeShutTime(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMDATETIMECHANGE pDTChange = reinterpret_cast <LPNMDATETIMECHANGE> (pNMHDR);
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
*pResult = 0;
}
void CAutoShutDownDlg::OnBnClickedRadio1()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
}
void CAutoShutDownDlg::OnBnClickedRadio2()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
}
void CAutoShutDownDlg::OnBnClickedRadio3()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
}
void CAutoShutDownDlg::OnBnClickedHide()
{
// TODO: 在此添加控件通知处理程序代码
ShowWindow(SW_HIDE);
m_IsShow = false;
}
void CAutoShutDownDlg::OnDestroy()
{
Shell_NotifyIcon(NIM_DELETE,&nid);
}
[解决办法]
那我把关机代码提炼出来吧 也不多
bool CAutoShutDownDlg::ShutDown()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return false;
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)
return false;
switch(m_Radio)
{
case 0:
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0))
return false;
break;
case 1:
if(!ExitWindowsEx(EWX_REBOOT | EWX_FORCE,0))
return false;
break;
case 2:
if(!ExitWindowsEx(EWX_LOGOFF | EWX_FORCE,0))
return false;
break;
}
return true;
}
[解决办法]
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace chkipsrv
{
public class Shudown
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport( "kernel32.dll ", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport( "advapi32.dll ", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport( "user32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool ExitWindowsEx(int DoFlag, int rea);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege ";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
private static void DoExitWin(int DoFlag)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(DoFlag, 0);
}
public static void Reboot()
{
DoExitWin(EWX_FORCE | EWX_REBOOT);
}
public static void PowerOff()
{
DoExitWin(EWX_FORCE | EWX_POWEROFF);
}
public static void LogOff()
{
DoExitWin(EWX_FORCE | EWX_LOGOFF);
}
}
}
引自:
http://www.chenjiliang.com/Article/View.aspx?ArticleID=2087&TypeID=84
[解决办法]
顶~
[解决办法]
class KernelApi
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport( "kernel32.dll ", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport( "advapi32.dll ", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport( "advapi32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport( "user32.dll ", ExactSpelling = true, SetLastError = true)]
internal static extern bool ExitWindowsEx(int flg, int rea);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege ";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
internal static void DoExitWin(int flg)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
}
}
//=======
DoExitWin()
填入预定义的参数