如何捕捉结束调整大小窗口?

How to catch the ending resize window?

提问人:Mediator 提问时间:12/18/2010 最后编辑:Dave ClemmerMediator 更新时间:6/19/2020 访问量:18777

问:

我需要在WPF中捕获事件endresize。

C# WPF XAML 调整窗口大小

评论


答:

30赞 Martin 12/18/2010 #1

WPF 不提供仅在调整大小过程结束时触发的事件。SizeChanged 是与窗口大小调整关联的唯一事件 - 它将在调整大小过程中多次触发。

一个完全的黑客方法是在 SizeChanged 事件触发时不断设置计时器滴答作响。然后计时器将没有机会滴答作响,直到调整大小结束,然后进行一次性处理。

public MyUserControl()
{
    _resizeTimer.Tick += _resizeTimer_Tick;
}

DispatcherTimer _resizeTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 1500), IsEnabled = false };

private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
{
    _resizeTimer.IsEnabled = true;
    _resizeTimer.Stop();
    _resizeTimer.Start();
}

void _resizeTimer_Tick(object sender, EventArgs e)
{
    _resizeTimer.IsEnabled = false;    

    //Do end of resize processing
}

评论

7赞 Hans Passant 12/18/2010
Winforms 中的 Form.ResizeBegin/End。通知仍然存在,但在 WPF 中被忽略。前进两步,后退一步。
2赞 nuclear sweet 5/11/2015
@Martin,请解释为什么你把 _resizeTimer.IsEnabled = true;在停止启动之前?这对我来说似乎毫无意义。
1赞 pjm 11/26/2017
我喜欢这种机制,因为它允许在用户暂停调整大小时进行一些处理。在用户调整大小时需要重新布局画布的情况。使用这种计时器方法,当用户停止移动鼠标(但未松开鼠标)时,可以执行重新布局,并可以看到新大小的影响。我的测试团队喜欢它而不是以前的 - 重新布局仅在鼠标释放时发生,即WM_EXITSIZEMOVE方法。我确实将计时器间隔设置为 200 毫秒,而不是此示例代码中使用的 1500 值。
16赞 Jesse Carter 5/7/2013 #2

Reactive Extensions for .NET 提供了一些非常酷的功能来处理标准事件模式,包括能够限制事件。我在处理大小更改事件时遇到了类似的问题,虽然解决方案仍然有些“黑客”,但我认为响应式扩展提供了一种更优雅的实现方式。这是我的实现:

IObservable<SizeChangedEventArgs> ObservableSizeChanges = Observable
    .FromEventPattern<SizeChangedEventArgs>(this, "SizeChanged")
    .Select(x => x.EventArgs)
    .Throttle(TimeSpan.FromMilliseconds(200));

IDisposable SizeChangedSubscription = ObservableSizeChanges
    .ObserveOn(SynchronizationContext.Current)
    .Subscribe(x => {
        Size_Changed(x);
    });

这将有效地限制事件,以便您的 Size_Changed 方法(您可以在其中执行自定义代码)不会执行,直到 200 毫秒(或您希望等待的时间)过去后才触发另一个事件。SizeChangedSizeChanged

private void Size_Changed(SizeChangedEventArgs e) {
    // custom code for dealing with end of size changed here
}
5赞 Bohoo 4/27/2016 #3

您可以准确检测 WPF 窗口大小调整的结束时间,并且不需要计时器。当用户在窗口调整大小移动操作结束时释放鼠标左键时,本机窗口将收到消息。WPF 窗口不会收到此消息,因此我们需要挂接一个将接收该消息的函数。我们可以使用 with 来获取我们的窗口句柄。然后,我们将钩子添加到我们的函数中。我们将在 window 事件(vb.net 代码)中完成所有这些操作:WM_EXITSIZEMOVEWndProcHwndSourceWindowInteropHelperWndProcLoaded

Dim WinSource As HwndSource    

Private Sub WindowLoaded_(sender As Object, e As RoutedEventArgs)

    WinSource = HwndSource.FromHwnd(New WindowInteropHelper(Me).Handle)
    WinSource.AddHook(New HwndSourceHook(AddressOf WndProc))
End Sub

现在,在我们的 中,我们将收听以下消息:WndProcWM_EXITSIZEMOVE

Const WM_EXITSIZEMOVE As Integer = &H232

Private Function WndProc(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr

    If msg = WM_EXITSIZEMOVE Then

        DoWhatYouNeed()
    End If

    Return IntPtr.Zero
End Function

这里这里解释了这种技术和类似的技术。

请注意,该函数应返回 IntPtr.Zero。此外,除了处理您感兴趣的特定消息外,不要在此函数中执行任何操作。

现在,也是在移动操作结束时发送的,我们只对调整大小感兴趣。有几种方法可以确定这是调整大小操作的结束。我通过收听消息(在调整大小时多次发送)和标志来做到这一点。整个解决方案如下所示:WM_EXITSIZEMOVEWM_SIZING

(注意:不要与此处突出显示的代码混淆,因为 vb.net 是错误的)

Dim WinSource As HwndSource
Const WM_SIZING As Integer = &H214
Const WM_EXITSIZEMOVE As Integer = &H232

Dim WindowWasResized As Boolean = False

Private Sub WindowLoaded_(sender As Object, e As RoutedEventArgs)

    WinSource = HwndSource.FromHwnd(New WindowInteropHelper(Me).Handle)
    WinSource.AddHook(New HwndSourceHook(AddressOf WndProc))
End Sub

Private Function WndProc(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr

    If msg = WM_SIZING Then

        If WindowWasResized = False Then

            'indicate the the user is resizing and not moving the window
            WindowWasResized = True
        End If
    End If

    If msg = WM_EXITSIZEMOVE Then

        'check that this is the end of resize and not move operation          
        If WindowWasResized = True Then

             DoWhatYouNeed()

             'set it back to false for the next resize/move
             WindowWasResized = False
        End If            
    End If

    Return IntPtr.Zero
End Function

就是这样。

评论

0赞 yumetodo 9/28/2017
我认为我们应该处理而不是处理。WM_ENTERSIZEMOVEWM_SIZING
6赞 Bilal 3/31/2020 #4

不需要计时器,使用非常干净的解决方案,@Bohoo,我只是将他的代码从 vb.net 改编为 c#

     public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.Loaded += MainWindow_Loaded;
            }

            private void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                // this two line have to be exactly onload
                HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
                source.AddHook(new HwndSourceHook(WndProc));
            }


            const int WM_SIZING = 0x214;
            const int WM_EXITSIZEMOVE = 0x232;
            private static bool WindowWasResized = false;


            private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
            {
                if (msg == WM_SIZING)
                {

                    if (WindowWasResized == false)
                    {

                        //    'indicate the the user is resizing and not moving the window
                        WindowWasResized = true;
                    }
                }

                if (msg == WM_EXITSIZEMOVE)
                {

                    // 'check that this is the end of resize and not move operation          
                    if (WindowWasResized == true)
                    {

                        // your stuff to do 
                        Console.WriteLine("End");

                        // 'set it back to false for the next resize/move
                        WindowWasResized = false;
                    }
                }

                return IntPtr.Zero;
            }

    }
0赞 Pavlo Datsiuk 6/19/2020 #5

对于具有 Rx 的 UWP (System.Reactive)

            //Stop window updates
            rootFrame = new Frame
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Width = Window.Current.Bounds.Width,
                Height = Window.Current.Bounds.Height
            };

            //updates after throttling
            var sizeChangedObservable = Observable.FromEventPattern<WindowSizeChangedEventHandler, WindowSizeChangedEventArgs>(
                      handler => Window.Current.SizeChanged += handler,
                      handler => Window.Current.SizeChanged -= handler);

            sizeChangedObservable.Throttle(TimeSpan.FromSeconds(0.35)).ObserveOnDispatcher(CoreDispatcherPriority.Normal).Subscribe(x =>
            {
                rootFrame.Width = x.EventArgs.Size.Width;
                rootFrame.Height = x.EventArgs.Size.Height;
            });