C# 使用c向程序发送击键,即使程序在后台也可以#

C# 使用c向程序发送击键,即使程序在后台也可以#,c#,winforms,winapi,desktop-application,keystrokes,C#,Winforms,Winapi,Desktop Application,Keystrokes,我想给一个程序发送按键,即使它在后台运行。但我只能用这样的记事本 [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 l

我想给一个程序发送按键,即使它在后台运行。但我只能用这样的记事本

[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);

但对于所有其他应用程序,如果它在后台,我不能发送击键。因为我不知道该程序的
lpszClass
(我想这是该程序中键入区域的用户控件名。对于记事本,它是
“编辑”
。我在网上找到了这个)

对于所有其他应用程序,我正在做的是,将应用程序置于前台,然后发送密钥,然后再次获取我的程序前台。我需要我的程序总是像前台一样运行

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

但这种方式是行不通的。一些键丢失,程序前台->后台->前台->后台。。。。。。喜欢它的舞蹈

如果在后台运行,如何向其他应用程序发送密钥。 或者是否有任何方法/来源可以找到程序的
lpszClass


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

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

以下是SetWindowsHookEX()的MSDN文档

这是一篇关于如何在C中实现这一点的知识库文章#

本文还将详细介绍:

不过,我预计你的应用程序作为键盘记录器会被各种间谍软件/反病毒软件捕获


祝您好运。

您可以使用检查工具(如)计算出程序的
lpszClass
。它为您提供了一个十字线,您可以在所需控件上拖动和定位十字线。这可以很容易地为我提供记事本的“编辑”类名


如果无法正常工作,请单击WinSpy++右下角的“更多>>”按钮,然后单击“定位”按钮查看控件层次结构;您可能需要将WM_KEYDOWN消息发布到某个父控件或子控件。

关于这一点,目前已有数百个问题,不确定您是如何错过它们的。无论你做什么让焦点切换回来,都不要这样做。这需要修改其他程序的能力,对吗?在这种情况下,他最好首先提供一个干净的API来做任何他需要的事情,而不是像发送按键消息或低级钩子这样的黑客行为。
[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