c# Detect mouse clicks anywhere (Inside and Outside the Form)

三世轮回 提交于 2020-06-24 15:57:06

问题


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){

...

}

回答1:


Here is a starter, if I understood your needs of "clicking from outside the window" and Hans Passant's suggestion doesn't fit your needs. You might need to add an event handler for 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();
    }
}

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




回答2:


When user clicks outside the form control, it losses the focus and you can make use of that.which means you have to use the _Deactivate(object sender, EventArgs e) event of the form control to make this work. Since which will trigger when the form loses focus and is no longer the active form. Let Form1 be the form, then the event will be like the following:

private void Form1_Deactivate(object sender, EventArgs e)
{
    // Your code here to handle this event
}


来源:https://stackoverflow.com/questions/49068445/c-sharp-detect-mouse-clicks-anywhere-inside-and-outside-the-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!