如何使用控件(例如按钮)从窗体调用事件

本文关键字:窗体 调用 事件 按钮 何使用 控件 | 更新日期: 2023-09-27 18:18:49

可能吗?我需要在这里调用Form1_FormClosing:

ContextMenu trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Close", delegate {
    Form1_FormClosing(????)
});

我需要它,因为我正在使用来自_FormClosing事件的CancelEventArgs:

private void Form1_FormClosing(object sender, CancelEventArgs e)
{
    if (th != null && th.ThreadState == System.Threading.ThreadState.Running)
    {
        if (MessageBox.Show("the process is running, you want stop it?", "app", MessageBoxButtons.OKCancel) == DialogResult.OK)
        {
            AbortProccess();                     }
        else
        {
            e.Cancel = true;
        }
    }
}

我希望这是清楚的,提前谢谢。

如何使用控件(例如按钮)从窗体调用事件

您可以做一些事情。首先,您可以使用myForm.Close()关闭表单,因为这将间接调用FormClosing事件。此外,您可以将FormClosing事件中的所有内容移动到单独的方法中,而不是在事件本身中。然后,您可以从事件和MenuItem中调用该方法。如果你不想这样做,你可以尝试使用这个作为委托:

//CancelEventArgs can also take a boolean which dictates if 
//it should be cancelled
Form1_FormClosing(this, new CancelEventArgs()); 

这在技术上是可能的,只需调用OnFormClosing()方法。但这并不会关闭表单,它只会在表单关闭时运行。当表单实际上没有关闭时,假装它正在关闭,这会导致失望。

所以直接调用Close()方法。

ContextMenu trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Close", delegate {
     this.Close();
});