【发布时间】:2012-01-06 20:38:40
【问题描述】:
我想获取用户在其他应用程序上按下的键。例如,在记事本中,而不是程序本身。这是我使用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# windows keyboard postmessage user32