如何在c#中发送鼠标事件到最小化窗体

本文关键字:事件 鼠标 最小化 窗体 | 更新日期: 2023-09-27 18:09:52

我尝试写一个简单的测试工具,它测试网站(win形式,使用WebBrowser控件)。我需要发送鼠标点击和击键到网站。它的作品时,形式是在顶部,但我想在后台运行测试。我如何发送鼠标点击,击键到最小化/背景表单?当前鼠标事件代码:

[DllImport( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall )]
public static extern void mouse_event( uint dwFlags, uint dx, uint dy, uint cButtons, UIntPtr dwExtraInfo );
[Flags]
public enum MouseEventFlags
{
    LEFTDOWN = 0x00000002,
    LEFTUP = 0x00000004,
    MIDDLEDOWN = 0x00000020,
    MIDDLEUP = 0x00000040,
    MOVE = 0x00000001,
    ABSOLUTE = 0x00008000,
    RIGHTDOWN = 0x00000008,
    RIGHTUP = 0x00000010
}
void mouseEvent( uint flag, Point p )
{
    p = caller.PointToScreen( p );
    Cursor.Position = p;
    mouse_event( flag, (uint) 0, (uint) 0, (uint) 0, (UIntPtr) 0 );
}
public void sendMouseClick( Point p )
{
    uint flag = (uint) MouseEventFlags.LEFTDOWN + (uint) MouseEventFlags.LEFTUP;
    mouseEvent( flag, p );
}

——编辑:

我尝试了SendMessage,但没有工作:(目前我尝试使用一个简单的从2个按钮,没有网页浏览器,只是正常的窗口。表单和按钮。当我按下button2时,我试图从代码中单击button1。:)

        // On the form, when i press the button 2 then minimize, wait, and try to press the button1
    private void button2_Click( object sender, EventArgs e)
    {
        // this.RaiseMouseEvent();
        MouseHelper mh = new MouseHelper(this.Text);
        this.WindowState = FormWindowState.Minimized;
        Thread.Sleep( 2000 );
        this.Refresh();
        Thread.Sleep(2000);
        mh.SendMouseClick( 25,25 );
    }
    private void button1_Click( object sender, EventArgs e )
    {
        throw new Exception( "BUTTON 1 CLICKED" );
    }
    // In the MouseHelper I call the left click
    public void SendMouseClick( int p_x, int p_y )
    {
        Int32 l_parm1 = (p_y << 16) | (p_x & 0xffff);
        SendMessage( windowPtr, WM_LBUTTONDOWN, 0, l_parm1 );
        SendMessage( windowPtr, WM_LBUTTONUP, 0, l_parm1 );
    }
    public MouseHelper( String windowTitle )
    {
        windowPtr = FindWindowByCaption( IntPtr.Zero, windowTitle );
    }
    // defintions
    public const uint WM_LBUTTONDOWN = 0x0201;
    public const uint WM_LBUTTONUP = 0x0202;
    [DllImport( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall )]
    public static extern int SendMessage(
        IntPtr hWnd,
        uint Msg,
        Int32 wParam,
        Int32 lParam
    );

我做错了什么?

它不工作,即使窗口没有最小化:(第一个解决方案工作时,窗口是活跃的,但第二个不:(我尝试了25,25和147,47 (PoinToScreen的25,25的结果)

如何在c#中发送鼠标事件到最小化窗体

可能SendMessage会工作。参见SendMessage和系统定义消息(更具体地说,在这里)

类似:

SendMessage(hwnd, WM_LBUTTONDOWN, 0, (123<<16)|(456));
SendMessage(hwnd, WM_LBUTTONUP, 0, (123<<16)|(456));