开发者

Click a button in another application

开发者 https://www.devze.com 2023-01-03 02:41 出处:网络
I want yo use Sen开发者_如何学运维dMessage or PostMessage to press a button in another app i have a sample code to do thisby getting Window Handle, but it doesn\'t work

I want yo use Sen开发者_如何学运维dMessage or PostMessage to press a button in another app

i have a sample code to do this by getting Window Handle, but it doesn't work

also i used "WinDowse" to get required info. here is the code

private const uint BM_CLICK = 0x00F5;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;

private void PushOKButton(IntPtr ptrWindow)
{
    WindowHandle = FindWindow(null, "Form1"); 
    if (ptrWindow == IntPtr.Zero)
      return;

    IntPtr ptrOKButton = FindWindowEx(ptrWindow, IntPtr.Zero, "Button", "&Yes");

    if (ptrOKButton == IntPtr.Zero)
      return;

    SendMessage(ptrOKButton, WM_LBUTTONDOWN, 0, 0);
    SendMessage(ptrOKButton, WM_LBUTTONUP, 0, 0);
    SendMessage(ptrOKButton, BM_CLICK, 0, 0);
}

is There a Compelete Suloution in c# ?


You have the right general idea. There are always tricks to automation.

Button Down/Up is preatty close to the raw action of clicking, but not quite the same. You will want to consider

  1. the coords where you click - some buttons don't like edge clicks at 0,0
  2. position of the mouse - mouse outside of the button at start or end can cause it to not work
  3. time to click - sometimes a quick click is ignored, add a small delay of say 10ms

BM_Click is an extra win32 message that is sent when doing a mouse click on a button - it's the shorter method and easier if the controls are the right type to use this alone.

Some effort is made to prevent things like using WM_GetText on password edits from foreign apps, be wary you may also have issues depending on the destination app.

Unfortunately I have no C# sample code for you right now.

Perhaps you might look into AutoIT to save some time.


Here is an Example of using the win32 API to drive the mouse - actually used for drag and drop selection of an area, but you could change the coords to mouse down/up inside the button.

POINT p;
BOOL cursorPosGetSuccessful = GetCursorPos(&p);
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, horA, verA, NULL, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, NULL, 0);
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, horB, verB, NULL, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, NULL, 0);
if (cursorPosGetSuccessful)// put the mouse back to roughly where it used to be before the scan.  
    mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, p.x, p.y, NULL, 0);
0

精彩评论

暂无评论...
验证码 换一张
取 消