关于在WinCE应用程序中实现关机和重启的功能
最近在开发WinCE应用程序过程中,想实现在程序中控制设备重启和关机的功能。通过查询资料,尝试通过调用kernel32.dll,advapi32.dll和user32.dll中函数实现。相关代码及函数如下:
这是引入动态链接库代码:
[DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess", SetLastError = true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll" , SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok );
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LookupPrivilegeValue(string host, string name, ref long pluid );
[DllImport("advapi32.dll", SetLastError = true) ]
public static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("user32.dll", SetLastError = true) ]
public static extern bool ExitWindowsEx(int flg, int rea);
public const int EWX_LOGOFF = 0x00000000; // 注消
public const int EWX_SHUTDOWN = 0x00000001; // 先保存再关机
public const int EWX_REBOOT = 0x00000002; // 重启
public const int EWX_FORCE = 0x00000004;//终止没响应程序
public const int EWX_POWEROFF = 0x00000008;//强制关机
public const int EWX_FORCEIFHUNG = 0x00000010;//不保存就关机
实现关机和重启的主要函数:
private void DoExitWin( int flg)
{
bool send;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
send = OpenProcessToken(hproc,TOKEN_ADJUST_PRIVILEGES |TOKEN_QUERY,ref htok );
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
send = LookupPrivilegeValue(null,SE_SHUTDOWN_NAME,ref tp.Luid);
send= AdjustTokenPrivileges(htok,false,ref tp,0,IntPtr.Zero,IntPtr.Zero);
send = ExitWindowsEx(flg,0);
}
应用程序上关机操作相应函数
private void button_Close_Click(object sender, System.EventArgs e)
{
DoExitWin(EWX_POWEROFF);
}
每次执行到红色字体表示的代码部分都会抛出一个System.MissingMethodException异常,请问怎么解决,高些答谢!
[解决办法]
ExitWindowsEx只有Windows Mobile 5以上才支持,另外PPC只能用它重启,SP才可以关机...
WinCE应该用KernelIoControl,一个简单例子...
[DllImport('Coredll.dll')]extern static int KernelIoControl(int dwIoControlCode, IntPtr lpInBuf, int nInBufSize, IntPtr lpOutBuf, int nOutBufSize, ref int lpBytesReturned);[DllImport('Coredll.dll')]extern static void SetCleanRebootFlag();public void HardReset(){int IOCTL_HAL_REBOOT = 0x101003C;int bytesReturned = 0;SetCleanRebootFlag();KernelIoControl(IOCTL_HAL_REBOOT,IntPtr.Zero,0, IntPtr.Zero, 0, ref bytesReturned);}
[解决办法]
LZ用的PC上的Win32API集,WinCE下一般是这个Coredll.dll,具体可以查MSDN,可以查到对应的API