我想获得用户在其他应用程序上按下的键。 例如,在记事本中,不是程序本身。 这里是我的编码,使用PostMessage
方法不断地发送键到记事本,但是,我希望当按下某个键时停止它。
using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; [DllImport("user32.dll")] public static extern IntPtr FindWindow( string ClassName, string WindowName); [DllImport("User32.dll")] public static extern IntPtr FindWindowEx( IntPtr Parent, IntPtr Child, string lpszClass, string lpszWindows); [DllImport("User32.dll")] public static extern Int32 PostMessage( IntPtr hWnd, int Msg, int wParam, int lParam); private const int WM_KEYDOWN = 0x100; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(Test)); t.Start(); } Boolean ControlKeyDown = true; public void Test() { // retrieve Notepad main window handle IntPtr Notepad = FindWindow("Notepad", "Untitled - Notepad"); if (!Notepad.Equals(IntPtr.Zero)) { // retrieve Edit window handle of Notepad IntPtr Checking = FindWindowEx(Notepad, IntPtr.Zero, "Edit", null); if (!Checking.Equals(IntPtr.Zero)) { while (ControlKeyDown) { Thread.Sleep(100); PostMessage(Checking, WM_KEYDOWN, (int)Keys.A, 0); } } } }
因此,当用户在记事本中按下X
键时,我的想法是将ControlKeyDown
设置为false
。 经过互联网的研究,我发现了这个代码并编辑了:
protected override void OnKeyDown(KeyEventArgs kea) { if (kea.KeyCode == Keys.X) ControlKeyDown = false; }
是的,由此,它肯定会停止循环,但这不是我想要的,因为当用户在程序上按下X
键而不是在记事本中时,它将停止循环。 这是因为KeyEventArgs
是System.Windows.Forms.KeyEventArgs
而不是记事本。
需要帮忙 :(
我想你正在寻找键盘挂钩。 看到这篇文章 ,它是C ++,但你似乎是灵活的P /调用,所以你可能会得到如何移植它很容易。
您可能需要查看user32.dll中的SetWindowsHookEx函数。
我也使用gma.UserActivity库在一个项目中做到这一点。