c#检测鼠标单击的任何地方(在窗体的内部和外部) [英] c# Detect mouse clicks anywhere (Inside and Outside the Form)

查看:657
本文介绍了c#检测鼠标单击的任何地方(在窗体的内部和外部)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在if语句中的任何位置(表单内和表单外)检测鼠标单击(左/右)?

Is this possible to detect a mouse click (Left/Right) anywhere (Inside and Outside the Form) in an if statement? And ff it's possible, how?

if(MouseButtons.LeftButton == MouseButtonState.Pressed){

...

}


推荐答案

<如果我理解您从窗户外面点击的需求,而汉斯·帕桑特(Hans Passant)的建议不符合您的需求,这是一个入门者。您可能需要为 Form1_Click 添加事件处理程序。

public partial class Form1 : Form
{
    private Mutex checking = new Mutex(false);
    private AutoResetEvent are = new AutoResetEvent(false);

    // You could create just one handler, but this is to show what you need to link to
    private void Form1_MouseLeave(object sender, EventArgs e) => StartWaitingForClickFromOutside();
    private void Form1_Leave(object sender, EventArgs e)      => StartWaitingForClickFromOutside();
    private void Form1_Deactivate(object sender, EventArgs e) => StartWaitingForClickFromOutside();
    private void StartWaitingForClickFromOutside()
    {
        if (!checking.WaitOne(10)) return;

        var ctx = new SynchronizationContext();
        are.Reset();

        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                if (are.WaitOne(1)) break;
                if (MouseButtons == MouseButtons.Left)
                {
                    ctx.Send(CLickFromOutside, null);
                    // You might need to put in a delay here and not break depending on what you want to accomplish
                    break;
                }
            }
            checking.ReleaseMutex();
        });
    }
    private void CLickFromOutside(object state) => MessageBox.Show("Clicked from outside of the window");
    private void Form1_MouseEnter(object sender, EventArgs e) => are.Set();
    private void Form1_Activated(object sender, EventArgs e)  => are.Set();
    private void Form1_Enter(object sender, EventArgs e)      => are.Set();
    private void Form1_VisibleChanged(object sender, EventArgs e)
    {
        if (Visible) are.Set();
        else StartWaitingForClickFromOutside();
    }
}

如果我对您的理解不正确,您可能会发现这很有用:将子控件的click事件传递给父控件

If I understood you incorrectly, you might find this useful: Pass click event of child control to the parent control

这篇关于c#检测鼠标单击的任何地方(在窗体的内部和外部)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆