按条件点击表单

本文关键字:表单 条件 | 更新日期: 2023-09-27 18:20:22

我有一个表单,它有各种按钮和面板。我有一个按钮,当按下它时,它会对一些值进行检查,如果检查通过,我需要点击鼠标穿过表单,然后点击应用程序窗口下面的任何内容。

我目前正在做的是在按下按钮并通过检查后,我使用将表单设置为透明

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
private int oldWindowLong = 0;
public void SetFormTransparent(IntPtr Handle)
{
    oldWindowLong = GetWindowLong(Handle, -20);
    SetWindowLong(Handle, -20, Convert.ToInt32(oldWindowLong | 0x80000 | 0x20));
}
public void SetFormNormal(IntPtr Handle)
{
    SetWindowLong(Handle, -20, Convert.ToInt32(oldWindowLong | 0x80000));
}

然后我创建了一个1毫秒的计时器,我用模拟鼠标点击

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);

并将表单恢复正常。这会导致非常不一致的行为,有时甚至是缓慢/无反应的行为。

如果我想在按钮检查通过后立即模拟鼠标单击,我还有什么其他选项?

按条件点击表单

重点是使用Color.Magenta作为表单的TransparencyKeyBackColor。然后使按钮不可见,并模拟单击事件,然后使按钮再次可见。

在这个例子中,当你点击按钮时,它会使表单透明,然后模拟点击通过表单

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
public void PerformClick()
{
    uint X = (uint)Cursor.Position.X;
    uint Y = (uint)Cursor.Position.Y;
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
private void button1_Click(object sender, EventArgs e)
{
    //Just to keep the form on top
    this.TopMost = true;
    //Make form transparent and click through
    this.TransparencyKey = Color.Magenta;
    this.BackColor = Color.Magenta;
    //Make the button invisible and perform a click
    //The click reaches behind the button
    //Then make button visible again to be able handle clicks again
    this.button4.Visible = false;
    PerformClick();
    this.button4.Visible = true;
}

票据

透明化并点击通过
要使窗体透明并使单击通过窗体,只需将窗体的TransparencyKey属性和BackColor属性设置为相同的颜色Color.Magenta

注意,关键是使用品红色作为TransparencyKeyBackColor。例如,如果使用"红色",它会使窗体透明,但不会使窗体点击通过。

如果您的表单上有一些控件,它们将保持可见,并将收到单击。如果您需要使它们不可见,您可以简单地将它们的Visible属性设置为false

使正常
为了使该形式正常,将BackColor设置为不同于TransparencyKey的另一种颜色就足够了,例如SystemColors.Control