【问题标题】:Add functionality to Windows.Forms exit button?向 Windows.Forms 退出按钮添加功能?
【发布时间】:2010-07-02 07:15:43
【问题描述】:

在 C#.NET 4.0 中编程是我最近的爱好,我想知道如何向标准 Windows.Forms 退出按钮(表单右上角的红色 X)添加功能。

我找到了一种禁用按钮的方法,但由于我认为它会影响用户体验,我想改为连接一些功能。

如何禁用退出按钮:

    #region items to disable quit-button
    const int MF_BYPOSITION = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    #endregion 

...

    private void DatabaseEditor_Load(object sender, EventArgs e)
    {
        this.graphTableAdapter.Fill(this.diagramDBDataSet.Graph);
        this.intervalTableAdapter.Fill(this.diagramDBDataSet.Interval);

        // Disable quit-button on load
        IntPtr hMenu = GetSystemMenu(this.Handle, false);
        int menuItemCount = GetMenuItemCount(hMenu);
        RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    }

但是在应用程序使用标准退出按钮退出之前,我到底如何附加一个方法。我想在退出 windows 窗体之前 XmlSerialize 一个列表。

【问题讨论】:

    标签: c# winforms button exit


    【解决方案1】:

    如果要在表单关闭前编写代码,请使用 FormClosing 事件

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
    
        }
    

    【讨论】:

      【解决方案2】:
      private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
      {
         if(MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
         {
             e.Cancel = true;
         }
      }
      

      【讨论】:

      • 为了记录,事件被称为FormClosing,所以当使用属性检查器添加方法时,它调用方法Form1_FormClosing。我不明白为什么没有“Closing”事件,并意识到它实际上是“FormClosing”。
      【解决方案3】:

      我发现最好的方法实际上是创建一个 EventHandler 来调用你想要调用的方法。

      在构造函数中:

      this.Closed += new EventHandler(theWindow_Closed);
      

      然后你创建方法:

      private void theWindow_Closed(object sender, System.EventArgs e)
      {
          //do the closing stuff
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-04
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 2021-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多