///
/// 停止此服务。
///
protectedoverridevoid OnStop()
{
if (threadForm !=null)
{
if (threadForm.IsAlive)
{
threadForm.Abort();
threadForm =null;
}
}
}
void FormShow()
{
GetDesktopWindow();
IntPtr hwinstaSave = GetProcessWindowStation();
IntPtr dwThreadId = GetCurrentThreadId();
IntPtr hdeskSave = GetThreadDesktop(dwThreadId);
IntPtr hwinstaUser = OpenWindowStation("WinSta0", false, 33554432);
if (hwinstaUser == IntPtr.Zero)
{
RpcRevertToSelf();
return;
}
SetProcessWindowStation(hwinstaUser);
IntPtr hdeskUser = OpenDesktop("Default", 0, false, 33554432);
RpcRevertToSelf();
if (hdeskUser == IntPtr.Zero)
{
SetProcessWindowStation(hwinstaSave);
CloseWindowStation(hwinstaUser);
return;
}
SetThreadDesktop(hdeskUser);
IntPtr dwGuiThreadId = dwThreadId;
Form1 f =new Form1(); //此FORM1可以带notifyIcon,可以显示在托盘里,用户可点击托盘图标进行设置
System.Windows.Forms.Application.Run(f);
dwGuiThreadId = IntPtr.Zero;
SetThreadDesktop(hdeskSave);
SetProcessWindowStation(hwinstaSave);
CloseDesktop(hdeskUser);
CloseWindowStation(hwinstaUser);
}
[DllImport("user32.dll")]
staticexternint GetDesktopWindow();
[DllImport("user32.dll")]
staticextern IntPtr GetProcessWindowStation();
[DllImport("kernel32.dll")]
staticextern IntPtr GetCurrentThreadId();
[DllImport("user32.dll")]
staticextern IntPtr GetThreadDesktop(IntPtr dwThread);
[DllImport("user32.dll")]
staticextern IntPtr OpenWindowStation(string a, bool b, int c);
[DllImport("user32.dll")]
staticextern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags,
bool fInherit, uint dwDesiredAccess);
[DllImport("user32.dll")]
staticextern IntPtr CloseDesktop(IntPtr p);
[DllImport("rpcrt4.dll", SetLastError =true)]
staticextern IntPtr RpcImpersonateClient(int i);
[DllImport("rpcrt4.dll", SetLastError =true)]
staticextern IntPtr RpcRevertToSelf();
[DllImport("user32.dll")]
staticextern IntPtr SetThreadDesktop(IntPtr a);