简体   繁体   中英

Showing MessageBox on MouseDown eats up MouseUp event

I am working on a WPF application where i handled a mouse down event which eventually shows up MessageBox.. But after MessageBox appears on mouseDown, it eats up corresponding MouseUp event of a control.

Scenario can be easily reproduced by simply handling MouseDown and MouseUP event in WPF window as:-

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
   MessageBox.show("Hello, Mouse down");
}

private void Window_MouseUP(object sender, MouseButtonEventArgs e)
{
   MessageBox.show("Hello, Mouse Up");
}

MouseUp message is never shown, once messagebox appears on MouseDown event.

What about initializing a new instance of System.Threading.Thread to call the MessageBox so that the main user interface thread would not be interrupted by the prompt?

Example

private void Window_MouseDown(object sender, MouseEventArgs e)
{
    Thread mythread = new Thread(() => MessageBox.Show("Hello, Mouse Down")); //Initialize a new Thread to show our MessageBox within 
    mythread.Start(); //Start the thread
}

private void Window_MouseUP(object sender, MouseEventArgs e)
{
    Thread mythread = new Thread(() => MessageBox.Show("Hello, Mouse Up")); //Initialize a new Thread to show our MessageBox within 
    mythread.Start(); //Start the thread
}

Screenshot

在另一个线程中调用MessageBox以避免中断主用户界面线程

Thanks,
I hope you find this helpful :)

As the commenter on your original post said, it seems that what's happening here is that the user's mouse wanders out of focus to click in the message box, or even just to display it, so the mouse moves "up" anyway - the event is never called. If you're just wanting to display messageboxes, then simply using:

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
   MessageBox.show("Hello, Mouse down");
   MessageBox.show("Hello, your mouse must be up because you've shifted focus!");
}

should do the job. If this behaviour repeats for something like changing a window title, or anything that doesn't require user input, then this could be a problem, but I am 100% sure that this is just an issue with regards to the MessageBox. Hope this helped.

@picrofo solution is also good and easy but i did by this way

  DialogResult result;
 private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        string message = "would you like to see mouse up event?";
        string caption = "event trick";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;

        result = MessageBox.Show(message, caption, buttons);
        textBox1.Text = result.ToString();
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            button1_MouseUp(sender, e);

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM