Skip to main content
 首页 » 编程设计

c#之ShowDialog() 后窗体隐藏在其他窗体后面

2024年02月06日13bjzhanghao

我在我的应用程序中使用了一个自定义的 Messagebox,它继承自 Form 类。当我在我的主窗体上使用它时它工作正常。但是,当我在从主窗体弹出的窗体上使用它的 Show() 函数时,Messagebox 隐藏在第二个窗体下,因此程序变得不可用。

即使我在 ShowDialog() 之前使用它的 BringToFront() 函数,它仍然会返回。 这是这个自定义消息框的 Show() 函数。如有必要,我可以分享更多它的代码:

public static DialogResult Show(string message, string title) 
{ 
    _msgBox = new MsgBox(); 
    _msgBox._lblMessage.Text = message; 
    _msgBox._lblTitle.Text = title; 
    _msgBox.Size = MsgBox.MessageSize(message); 
 
    MsgBox.InitButtons(Buttons.OK); 
    //_msgBox.BringToFront(); 
    _msgBox.ShowDialog(); 
    return _buttonResult; 
} 

MsgBox 是类本身的名称:

class MsgBox : Form 

请您参考如下方法:

尝试为您的内部消息框类传递 Owner 值

public static DialogResult Show(string message, string title, Form owner = null) 
{ 
    _msgBox = new MsgBox(); 
    _msgBox._lblMessage.Text = message; 
    _msgBox._lblTitle.Text = title; 
    _msgBox.Size = MsgBox.MessageSize(message); 
 
    MsgBox.InitButtons(Buttons.OK); 
    if(owner != null) 
        _msgBox.ShowDialog(owner); 
    else 
        _msgBox.ShowDialog(); 
    return _buttonResult; 
} 

使用默认参数,您可以仅在需要的地方更改代码。

经过一些研究,我找到了 this question and its answers这稍微解释了这种行为