即使使用C#在后台,将击键发送到程序中
-
11-10-2019 - |
题
我想将密钥冲程发送到程序中,即使它在后台运行。但是我只能为此做到这一点,
[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
该程序(我认为这是该程序中打字区域的USERCORTROL名称。对于记事本,它是 "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
但是这种方式不起作用。一些钥匙被错过了,该程序前景 - > Background-> foregound->背景……就像它的跳舞...
如果其在后台运行,如何将密钥发送到其他应用程序。或有任何方法/来源可以找到 lpszClass
程序?
抱歉,如果我错过了任何必需的信息。这是一个大型应用程序。我在这里仅发布了需要的零件。如果有人需要任何其他信息,请问。
解决方案
您也许可以弄清楚 lpszClass
使用检查工具,例如 Winspy ++. 。它为您提供了一个可以在所需控件上拖动和定位的十字路口。这可以轻松地为我提供记事本的“编辑”类名称。
如果事情不起作用,请单击WinSpy ++右下方的“更多>>”按钮,然后单击“定位”按钮以查看控制层次结构;您可能需要将WM_KEYDOWN消息发布到父母或子女控件之一。
其他提示
我认为您需要通过Win32函数SetWindowShookex()安装背景程序安装低级键盘钩。
这是SetWindowShookex()的MSDN文档
http://msdn.microsoft.com/en-us/library/ms644990(V=VS.85).aspx
这是KB的文章,介绍了如何从C#做到这一点
http://support.microsoft.com/kb/318804
本文也详细介绍了: http://www.codeguru.com/columns/vb/article.php/c4829
我希望您的应用程序将被各种间谍软件/防病毒软件作为键盘记录器所吸引。
祝你好运。