Nikita B
Nikita B

Reputation: 3333

How to release mouse captured by wpf control when clicking on winforms control

I have a winforms application which hosts a wpf control. At some point wpf control captures the mouse. I want to release it when the mouse is clicked outside the control. I am aware that I can subscribe to PreviewMouseDownOutsideCapturedElement event or subscribe to PreviewMouseDown and perform a hit test. And then release mouse capture in the event handler.

What I do not know, is how can I let the mouse click go through after I release the mouse? For example, if I click on winforms button when the mouse is captured by wpf control, I want to do both - release mouse and click the button. Because right now I have to perform a double click to press a button: first click cancels capture, and the second one presses the button. I would like to know if there is a way avoid it.

Upvotes: 2

Views: 2587

Answers (1)

Nikita B
Nikita B

Reputation: 3333

As there were no responses i solved my issue by emulating mouse click using winapi:

AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, 
                   new MouseButtonEventHandler((s, e) =>
                       {
                           Mouse.Capture(null);
                           if (e.LeftButton == MouseButtonState.Pressed)
                           {
                               MouseInterop.LeftClick();
                           }
                        }));


public static class MouseInterop
{
    public static void LeftClick()
    {
        var x = (uint) Cursor.Position.X;
        var y = (uint) Cursor.Position.Y;
        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
    }

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

    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
}

This is clearly a hack by i failed to find a better way.

Edit:

Coming back to this question. The above approach has side effects which kind of make it unusable. For example, when you capture the mouse with WPF control, all the MouseOver effects are disabled for other parts of your application.

I actually ended up using local mouse and keyboard hooks, instead of mouse capture.

Upvotes: 0

Related Questions