简体   繁体   English

消息框模态

[英]Message Boxes Modal

I've been working at this on and off for a while but essentially I have a class that I call to display message boxes. 我已经在这上面工作了一段时间,但实际上我有一个类可以显示消息框。

I'm trying to get my message boxes to be modal, which is easily done if you specify the form to be modal to. 我正在尝试使我的消息框具有模式性,如果您将表单指定为模式,则很容易做到。

So my form is declared like this 所以我的表格是这样声明的

public partial class MainForm : Form

and it is instantiated like this 像这样实例化

var mainForm = new MainForm();

So I have a class that contains methods which open message boxes like this 因此,我有一个类,其中包含打开像这样的消息框的方法

MainForm.ActiveForm.Invoke(new MethodInvoker(delegate
{
    MessageBox.Show(MainForm.ActiveForm, message, title, buttons, icon);
}));

This works fine, but active form only works when the form is active..... 这可以正常工作,但是活动表单仅在表单处于活动状态时才有效。

Anyways is there an easy way around this? 无论如何,有一个简单的方法吗?

I'm kind of a C# newbie, but aren't MessageBoxes already modal? 我是C#的新手,但是MessageBoxes已经不是模态了吗? And if you were making your own messagebox, couldn't you just do messageboxform.ShowDialog(); 而且,如果您要创建自己的消息框,则不能只执行messageboxform.ShowDialog(); ?

This is working for me: 这为我工作:

MessageBox.Show(Form.ActiveForm,"Finished processing", "Process finished", , MessageBoxButtons.OK, MessageBoxIcon.Information);

Form.ActiveForm would give you the currently active form, even if you are raising your MessageBox from any other class. Form.ActiveForm会给您当前处于活动状态的表单,即使您从任何其他类中引发MessageBox也不例外。

If all you want to do is avoid using that first parameter, the msdn has a few Show methods for a Winforms Messagebox. 如果您要做的就是避免使用第一个参数,则msdn具有一些Winforms消息框的Show方法。

You might try this one: 您可以尝试以下一种方法:

public static DialogResult Show(
    string text,
    string caption,
    MessageBoxButtons buttons,
    MessageBoxIcon icon,
    MessageBoxDefaultButton defaultButton
 )

So for you: 所以对你来说:

MessageBox.Show(message, title, buttons, icon);

Edit: I believe this should appear modal (without that first parameter) because it's being invoked from the main form. 编辑:我认为这应该是模态的(没有第一个参数),因为它是从主窗体调用的。

I have a solution that works fairly well, but I'm not sure if there is a more elegant solution. 我有一个效果很好的解决方案,但是我不确定是否有更好的解决方案。

So in MainForm.cs I have 所以在MainForm.cs中

public static Form mainWindow { get; private set; }

Then in the OnLoad method 然后在OnLoad方法中

Focus();
BringToFront();
mainWindow = MainForm.ActiveForm;

Then in my message box method: 然后在我的消息框方法中:

MainForm.mainWindow.Invoke(new MethodInvoker(delegate
{
    MainForm.mainWindow.BringToFront();
    MessageBox.Show(MainForm.mainWindow, message, title, MessageBoxButtons.OK, icon);
}));

Am I missing something here? 我在这里想念什么吗? Is there a better alternative to mainWindow = MainForm.ActiveForm? 有没有更好的替代方法mainWindow = MainForm.ActiveForm?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM