Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using PostMessage

I'm trying to send a key to an application. I tested the Handlewindow value used breakpoints to understand what I'm doing wirong but i cant find a solution. To be more detailed, its a little game and when I activate the chatbar ingame, the key I want to send will be written there, but I want to make it functionaly when I am playing to use the commands. The game doesnt have a guard or some protections.

Here is my code:

[DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

    const uint WM_KEYDOWN = 0x0100;

    private void button1_Click(object sender, EventArgs e)
    {
        string pName = textBox1.Text;


        //Get Processes
        Process[] processes = Process.GetProcessesByName(pName);

        //Main part
        foreach (Process p in processes)
            if (p.ProcessName == (string)pName)
            {
                    PostMessage(p.MainWindowHandle, WM_KEYDOWN, (int)Keys.W, 0);
            }


    }

Like I said, it can be sent 1000000 times successfully but nothing happens. Is there another way how I can send keys to an Windows application that works minimized or even hidden? It should be only send to my app.

like image 782
Noli Avatar asked May 15 '26 06:05

Noli


2 Answers

Just note that the correct import of PostMessage is:

[DllImport("user32.dll")]
static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

Sending the keys like you are doing might not work, but you can use spy++ to capture the actual messages that are being posted to the application by windows and use those.

https://learn.microsoft.com/en-us/visualstudio/debugger/introducing-spy-increment?view=vs-2022

like image 139
critic Avatar answered May 16 '26 20:05

critic


If i understand correctly, you want to send keys to a game. In this case i think that the game is not fetching the keys from the Windows Message queue, it is probably reading the keyboard status directly using DirectX or similar ways.

See this similar question:

Send Key Strokes to Games

like image 38
Zmaster Avatar answered May 16 '26 20:05

Zmaster