C# - keydown event when form is not active

时间:2018-05-28 18:44:38

标签: c# events keydown

Hi I am making an application sort of like a mouse macro where when you press F it will move the mouses position between two spots, everything works the only issue I am running into is that I want this to work in the background as in when the form isnt pulled up on my screen. How can I do this? If anyone can help me that would be awesome.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F)
    {
        PointConverter pc = new PointConverter();
        Point pt = new Point();
        pt = (Point)pc.ConvertFromString("60, 700");
        Cursor.Position = pt;
        System.Threading.Thread.Sleep(5000);
        pt = (Point)pc.ConvertFromString("600, 700");
        Cursor.Position = pt;
    }

1 个答案:

答案 0 :(得分:0)

事件仅在表单处于活动状态时才适用。您不能在后台使用表单中的事件。而是使用GetKeyState功能 https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
看看虚拟键码也是如此。我做了一个应用程序,在后台监听按键一次。我必须在循环中使用GetKeyState来检查每个虚拟键代码以查看是否已按下它。但听起来像您的应用程序,您只需要检查您想要听的热键 你需要在后台为你的循环运行一个线程,或者使用一个计时器。

CNC中 这里有一些代码来实现GetKeyState函数。

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern byte GetKeyState(int nVirtKey);