我终于在 CodeProject 上找到了this C++ code,它在以系统用户身份启动时运行良好。因此,我将代码转换为dll,并从我的代码中调用了该函数。
这是 c++ 代码(您可以使用 ErrorExit 示例函数,该函数使用 MSDN 中的 GetLastError 以防出现问题):
#include "windows.h"
#include <strsafe.h>
__declspec(dllexport) BOOL SimulateAltControlDel()
{
HDESK hdeskCurrent;
HDESK hdesk;
HWINSTA hwinstaCurrent;
HWINSTA hwinsta;
//
// Save the current Window station
//
hwinstaCurrent = GetProcessWindowStation();
if (hwinstaCurrent == NULL)
return FALSE;
//
// Save the current desktop
//
hdeskCurrent = GetThreadDesktop(GetCurrentThreadId());
if (hdeskCurrent == NULL)
return FALSE;
//
// Obtain a handle to WinSta0 - service must be running
// in the LocalSystem account
//
hwinsta = OpenWindowStation("winsta0", FALSE,
WINSTA_ACCESSCLIPBOARD |
WINSTA_ACCESSGLOBALATOMS |
WINSTA_CREATEDESKTOP |
WINSTA_ENUMDESKTOPS |
WINSTA_ENUMERATE |
WINSTA_EXITWINDOWS |
WINSTA_READATTRIBUTES |
WINSTA_READSCREEN |
WINSTA_WRITEATTRIBUTES);
if (hwinsta == NULL)
return FALSE;
//
// Set the windowstation to be winsta0
//
if (!SetProcessWindowStation(hwinsta))
return FALSE;
//
// Get the default desktop on winsta0
//
hdesk = OpenDesktop("Winlogon", 0, FALSE,
DESKTOP_CREATEMENU |
DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE |
DESKTOP_HOOKCONTROL |
DESKTOP_JOURNALPLAYBACK |
DESKTOP_JOURNALRECORD |
DESKTOP_READOBJECTS |
DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS);
if (hdesk == NULL)
return FALSE;
//
// Set the desktop to be "default"
//
if (!SetThreadDesktop(hdesk))
return FALSE;
PostMessage(HWND_BROADCAST,WM_HOTKEY,0,MAKELPARAM(MOD_ALT|MOD_CONTROL,VK_DELETE));
//
// Reset the Window station and desktop
//
if (!SetProcessWindowStation(hwinstaCurrent))
return FALSE;
if (!SetThreadDesktop(hdeskCurrent))
return FALSE;
//
// Close the windowstation and desktop handles
//
if (!CloseWindowStation(hwinsta))
return FALSE;
if (!CloseDesktop(hdesk))
return FALSE;
return TRUE;
}
还需要在工程中添加.def文件才能正确导出函数(工程名为AltCtrlDelCpp)并告诉链接器模块的定义文件就是这个文件
;altctrldel.def
LIBRARY AltCtrlDelCpp
;CODE PRELOAD MOVEABLE DISCARDABLE
;DATA PRELOAD MOVEABLE
EXPORTS
SimulateAltControlDel
然后,在 .NET 解决方案中,将 dll 添加到项目中,对其进行配置,使其始终复制到输出目录中,然后使用 DllImport 导入函数:
C#代码
[DllImport(@"AltCtrlDelCpp.dll")]
static extern bool SimulateAltControlDel();
VB.NET 代码
<DllImport("AltCtrlDelCpp.dll")> _
Private Function SimulateAltControlDel() As Boolean
在 VB.NET 中,您还需要将属性添加到 Sub Main :
<MTAThread()> _
Sub Main()
然后你只需要调用SimulateAltControlDel 函数就可以了。请注意,我只为 控制台应用程序 使用了这项功能,它不适用于 winform 应用程序。