Click here to Skip to main content
15,891,761 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
Mouse Capture doesn't work:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Button button1 = new Button();
        button1.Width = 50;
        button1.Height = 20;

        this.Content = button1;

        Mouse.Capture(button1);
        button1.PreviewMouseDown += Down;
    }

    private void Down(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("Hello World!"); // doesn't show
    }
}
Posted
Updated 26-Apr-15 1:29am
v6
Comments
Sergey Alexandrovich Kryukov 26-Apr-15 12:43pm    
It does work. What did you try to achieve with that? Capturing a mouse in a constructor is absurd, of course.
—SA

Please see my comment to the question.

You are trying to capture the mouse to the element which is not even rendered. How could it possibly work? Mouse should be captured sometimes, but it should be done only temporarily, for relatively short period of time. For example, you can implement button-like behavior, if you capture mouse in its MouseDown event, to be able to handle a MouseUp event (for example), even when the mouse pointer goes out of the element's boundaries, but then the mouse should be un-captured in the handle on this second event immediately. This is just an example.

Please see:
https://msdn.microsoft.com/en-us/library/system.windows.uielement.capturemouse%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.windows.input.mouse.capture%28v=vs.110%29.aspx[^].

Read "Remarks" section thoroughly. Any questions?

—SA
 
Share this answer
 
Replace your code by the next to get it working:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Button button1 = new Button();
        button1.Width = 50;
        button1.Height = 20;

        this.Content = button1;

        this.Loaded += delegate { Mouse.Capture(button1); };
        button1.PreviewMouseDown += Down;
    }

    private void Down(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("Hello World!"); // shows
    }
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900