LocationChanged is not reliably called when the window is dragged

To implement docking, I relied on listening for the Window.LocationChanged event to detect the changing position of the window being moved across the screen. But the user reported that the dock is not working on their machine.

It turns out they turned off "Show window contents while dragging" in Windows performance options, and as a result, the LocationChanged event is only fired after the window has been dragged to its final position, not while the window is mid-flight.

I was wondering if there is an alternative way to detect window movements, a good way. I know I can pin up or hook up some horrible timer, but I was hoping for a better way, maybe there is a reliable listener event?

Here's a method to prevent any "you didn't submit any codes" / "what have you tried".

protected override void OnLocationChanged(EventArgs e)
{

}

      

+3


source to share


1 answer


Here's my solution,

Great job.



class MyWindow : Window
{
    private const int WM_MOVING = 0x0216;
    private HwndSource _hwndSrc;
    private HwndSourceHook _hwndSrcHook;

    public MyWindow()
    {
        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
    }

    void OnUnloaded(object sender, RoutedEventArgs e)
    {
        _hwndSrc.RemoveHook(_hwndSrcHook);
        _hwndSrc.Dispose();
        _hwndSrc = null;
    }

    void OnLoaded(object sender, RoutedEventArgs e)
    {
        _hwndSrc = HwndSource.FromDependencyObject(this) as HwndSource;
        _hwndSrcHook = FilterMessage;
        _hwndSrc.AddHook(_hwndSrcHook);
    }

    private IntPtr FilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case WM_MOVING:
                OnLocationChange();
                break;
        }

        return IntPtr.Zero;
    }

    private void OnLocationChange()
    {
        //Do something
    }
}

      

+2


source







All Articles