7

How can I simulate a button click in the sendmessage API in C#?

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
Prabodha Eranga
  • 71
  • 1
  • 1
  • 2
  • 1
    Possible duplicate of [Simulating Key Press c#](https://stackoverflow.com/questions/3047375/simulating-key-press-c-sharp) – Deniz Jun 15 '18 at 09:16

1 Answers1

14

C code:

#include <Windows.h>
//...
SendMessage(hWndButton, BM_CLICK, 0, 0);

C# code:

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

...
Button myButton = ...;
const int BM_CLICK = 0x00F5;
SendMessage(myButton.Handle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);

But be aware that, in C#, you can just as easily do:

myButton.PerformClick();
user541686
  • 205,094
  • 128
  • 528
  • 886
  • 1
    can u exaplin this futher please? – Prabodha Eranga Jan 12 '11 at 05:10
  • Sorry, that was a hint on the C version. The C# version is below. All you literally have to do is call that function with the correct `myButton`. – user541686 Jan 12 '11 at 05:13
  • 2
    There is absolutely *no* reason to use `SendMessage` to click a button in your own application (one that you can use `myButton.Handle` to get its handle). Every `Button` control in the .NET Framework has a [`PerformClick` method](http://msdn.microsoft.com/en-us/library/system.windows.forms.button.performclick.aspx) that you can use to simulate a button click. The *only* reason to use `SendMessage` is if you want to click a button in *another* application, in which case you're also going to have to P/Invoke `FindWindow` and `GetWindow` to determine that button's handle. – Cody Gray - on strike Jan 12 '11 at 05:28
  • @Lambert: Yes. I didn't downvote and don't mean to criticize your answer. It does in fact answer the question that was asked. I'm just commenting that there's very little use for this. Perhaps it should have been a comment to the question, but whatever. – Cody Gray - on strike Jan 12 '11 at 05:34
  • @Cody: Sorry I didn't mean to say you downvoted or anything. :) Yeah I guess I should've put that in my answer, I'll go change it; thanks. :) – user541686 Jan 12 '11 at 05:37
  • this is the scope of my problem. i want to call exe from the windows service.task of that exe file is to generate outut while displaying a cinfirmation messagge.but real senario wht happen is when service start exe file show the task manager but didnt create the out put. – Prabodha Eranga Jan 12 '11 at 05:38