C# - Use form instead of messagebox
I am working on an application for work and I need a customized 开发者_如何学运维messagebox to appear. I have created a simple form called Alert.cs that I have styled the way I want and added one button with a click method of this.Close(). now I want it to behave exactly like a standard messagebox.show(). I have the form showing but when I use the standard messagebox.show("text of alert") it waits to continue operation until the user click 'OK', this is what I want the form to do.
Use Form.ShowDialog();
. This allows the form to act the same way as a MessageBox
in the sense that it retains focus until closed.
You will need to implement a static method for your Alert class if you want the exact MessageBox-like behaviour.
public static DialogResult Show(string text)
{
Alert form = new Alert(text);
return form.ShowDialog();
}
Now you can use the form by calling:
Alert.Show("my message");
You can use a modal windows form. Something like
Form frm = new Form();
frm.ShowDialog(this);
See Form.ShowDialog Method
Shows the form as a modal dialog box with the currently active window set as its owner.
Displaying Modal and Modeless Windows Forms
You don't write how you currently display your Alert Form, but calling
alert.ShowDialog();
instead of alert.Show()
should do the trick.
The ShowDialog that takes an owner is an even better alternative:
alert.ShowDialog(owner);
精彩评论