【问题标题】:Get key pressed from other application C#从其他应用程序 C# 中获取按键
【发布时间】: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


    【解决方案1】:

    我猜你正在寻找键盘挂钩。 See this article,它是 c++,但你在 p/invoke 中似乎很敏捷,所以你可能知道如何轻松移植它。

    【讨论】:

      【解决方案2】:

      您可能想看看 user32.dll 中的 SetWindowsHookEx 函数。

      我还使用gma.UserActivity 库在项目中执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-19
        • 2016-12-26
        • 2014-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多