6

即使程序在后台运行,我也想将击键发送到程序。但我只能为这样的记事本做到这一点,

[DllImport("user32.dll")]
protected static extern byte VkKeyScan(char ch);

[DllImport("user32.dll", SetLastError = true)]
protected static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("User32.Dll", EntryPoint = "PostMessageA")]
protected static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

char Key = // key value to send

IntPtr hWnd = FindWindowEx(_handle, IntPtr.Zero, "edit", null);   // _handle is the windows handle of the program (here its notepad)
PostMessage(hWnd, WM_KEYDOWN, VkKeyScan(Key), 0);

但是对于所有其他应用程序,如果它在后台,我将无法发送击键。由于我不知道该lpszClass程序的名称(我认为这是该程序中键入区域的 userControl 名称。对于记事本来说是"edit"。我在网上冲浪时发现了这个)。

对于所有其他应用程序,我正在做的是将应用程序置于前台,然后发送密钥,然后再次将我的程序置于前台。我需要我的程序始终作为前台运行。

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

SetForegroundWindow(_handle);       // _handle is the windows handle of the program

System.Threading.Thread.Sleep(50);       // Waiting few milliseconds till application coming to foreground.                    
wsh.SendKeys(Key.ToString(), ref wait);  // wsh is WshShellClass wsh= new WshShellClass();
SetForegroundWindow(_mainHandle);    // _mainHandle is the windows handle of my application

但这种方式行不通。一些键丢失,程序前景->背景->前景->背景......就像它的舞蹈......

如果它在后台运行,如何将密钥发送到其他应用程序。或者有什么方法/来源可以找到lpszClass一个程序?

抱歉,如果我错过了任何必需的信息。这是一个大型应用程序。我在这里只发布了需要的部分。如果有人需要任何其他信息,请询问。

4

2 回答 2

3

我认为您需要让后台程序通过 win32 函数 SetWindowsHookEx() 安装低级键盘挂钩。

这是 SetWindowsHookEX() 的 MSDN 文档

http://msdn.microsoft.com/en-us/library/ms644990(v=vs.85).aspx

这是关于如何从 C# 执行此操作的知识库文章

http://support.microsoft.com/kb/318804

这篇文章也有一些细节:http: //www.codeguru.com/columns/vb/article.php/c4829

不过,我希望您的应用程序会被各种间谍软件/防病毒软件捕获为键盘记录器。

祝你好运。

于 2011-01-13T18:38:03.650 回答
2

您可以使用WinSpy++lpszClass等检查工具找出程序的原因。它为您提供了一个十字准线,您可以将其拖动并定位在所需的控件上。这能够轻松地为我提供记事本的“编辑”类名称。

如果还是不行,点击WinSpy++右下角的“更多>>”按钮,然后点击“定位”按钮查看控件层次结构;您可能需要将 WM_KEYDOWN 消息发布到父控件或子控件之一。

于 2011-01-13T18:41:02.877 回答