【问题标题】:Send Keystrokes to a program even if its in background using c#使用 c# 将按键发送到程序,即使它在后台
【发布时间】:2011-06-08 16:36:58
【问题描述】:

即使程序在后台运行,我也想将击键发送到程序。但我只能像这样对notepad做到这一点,

[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(我认为这是该程序中输入区域的用户控件名称。对于记事本,它是"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

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

【问题讨论】:

  • SO 已经有数百个关于此的问题,不知道您是如何错过的。无论你做什么来让注意力转移回来,都不要这样做。

标签: c# winforms winapi desktop-application keystrokes


【解决方案1】:

我认为您需要让后台程序通过 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

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

祝你好运。

【讨论】:

  • 这需要修改其他程序的能力,对吧?在这种情况下,他最好首先提供一个干净的 API 来做他需要的任何事情,而不是像发送按键消息或低级挂钩这样的黑客攻击。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2022-08-08
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多