Momo
Momo

Reputation: 482

Get key pressed from other application C#

I would like to get the key pressed by user on other application. For example, in notepad, not the program itself. Here is my coding that using PostMessage method to continuously send key to notepad but however, I wish to stop it when some key is pressed.

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);                                                             
            }
        }
    }
}

Hence, my idea is set the ControlKeyDown to false when user pressed X key in notepad. After research through internet, I found out this code and edited:

protected override void OnKeyDown(KeyEventArgs kea)
{
    if (kea.KeyCode == Keys.X)
    ControlKeyDown = false;
}

Yes, by this, it definitely will stop the looping but this is not I want as it will stop the loop when user presses X key on the program but not in notepad. This is because the KeyEventArgs is System.Windows.Forms.KeyEventArgs and not Notepad.

Need help :(

Upvotes: 1

Views: 3049

Answers (2)

Gabriel GM
Gabriel GM

Reputation: 6639

You might want to take a look at the SetWindowsHookEx function in the user32.dll.

I also user the gma.UserActivity library to do it in a project.

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

I guess you are looking for keyboard hooking. See this article, it is c++ but you appear to be agile in p/invoke so you probably get how to port it easily.

Upvotes: 2

Related Questions