移动表单时如何停止 ResizeEnd 事件?

Sha*_*hah 6 winforms

我在表单ResizeEnd事件中编写了某些代码。现在的问题是,当通过单击并拖动标题栏来移动表单时,ResizeEnd即使表单大小未更改,也会触发事件并执行代码。

我浏览了Resizeend事件的 MSDN 文档,它说当表单移动时事件将触发(不明白为什么在大小未更改时会发生这种情况)。

为了解决问题,我设置了 if 条件来检查大小是否发生更改,如下所示,以停止在表单移动时执行代码:

int Prv_Height; int Prv_Width;
private void TemplateGrid_ResizeEnd(object sender, EventArgs e)
{
    if (this.Size.Width != Prv_Width || this.Size.Height != Prv_Height)
    {
        Prv_Width = this.Size.Width;
        Prv_Height = this.Size.Height;
        //Other code here when form resize ends...
    }
}
Run Code Online (Sandbox Code Playgroud)

那么有什么方法可以ResizeEnd在表单移动时阻止事件触发呢?或者有其他更好的方法来解决问题?

小智 0

您可以将尺寸更改检查移至新的基本表单。在派生窗体上,只有在实际更改大小时才会触发 resizeEnd 事件。

public partial class CustomForm : Form
{                       
    private Size _prvSize;

    public CustomForm()
    {
        InitializeComponent();        
    }

    protected override void OnShown(EventArgs e)
    {
        _prvSize = this.Size;
        base.OnShown(e);
    }

    protected override void OnResizeEnd(EventArgs e)
    {
        if (this.Size == _prvSize)
            return;

        _prvSize = this.Size;
        base.OnResizeEnd(e);
    }

}
Run Code Online (Sandbox Code Playgroud)