MessageBox.Show使用
if (MessageBox.Show("请确认退出?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
MessageBox.Show有21种使用方法,其中
string text, 文本
string caption, 标题
System.Windows.Forms.MessageBoxButtons buttons, 指定在消息框中显示哪些按钮。
System.Windows.Forms.MessageBoxIcon icon 指定在消息框中显示哪个图标
这四个是最常使用的参数。
System.Windows.Forms.MessageBoxDefaultButton defaultButton 指定消息框中的默认按钮
System.Windows.Forms.MessageBoxOptions options 可指定将对消息框使用哪些显示和关联选项。若要使用默认值,请传入 0。
bool displayHelpButton 如果显示“帮助”按钮,则为 true;否则为 false。 默认值为 false。
string helpFilePath 用户单击“帮助”按钮时显示的“帮助”文件的路径和名称
这四个参数有时也会用到,其他的暂时没用到
返回值:DialogResult类型
在屏幕的最前面弹出消息框
MessageBox.Show("要弹的信息。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
ServiceNotification 消息框显示在活动桌面上。
调用方是一种服务,用于将事件通知用户。即使没有用户登录到计算机,该功能也会在当前活动桌面上显示一个消息框。
DefaultDesktopOnly 消息框显示在活动桌面上。
此常数与 ServiceNotification 相同,只是系统仅在交互窗口站的默认桌面上显示消息框。
DefaultDesktopOnly 将使引发 MessageBox 的应用程序失去焦点。 显示的 MessageBox 将不使用视觉样式。
RightAlign 消息框文本右对齐。
RtlReading 指定消息框文本按从右到左的阅读顺序显示。
消息框淡出
似乎得使用窗体达到效果
窗体参考资料:几种窗口淡入淡出效果代码
自动关闭消息框
调用WinAPI
public class MessageTip
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public const int WM_CLOSE = 0x10;
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public static bool HasMessageBox(string caption)
{
IntPtr dlg = FindWindow(null, caption);
if (dlg == IntPtr.Zero)
return true;
else
return false;
}
public void ShowMessageBoxTimeout(string text, string caption, MessageBoxButtons buttons, int timeout)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox), new CloseState(caption, timeout));
MessageBox.Show(text, caption, buttons);
}
private void CloseMessageBox(object state)
{
CloseState closeState = state as CloseState;
Thread.Sleep(closeState.Timeout);
IntPtr dlg = FindWindow(null, closeState.Caption);
if (dlg != IntPtr.Zero)
{
SendMessage(dlg, WM_CLOSE, 0, 0);
}
}
private class CloseState
{
private int _Timeout;
/// <summary>
/// In millisecond
/// </summary>
public int Timeout
{
get
{
return _Timeout;
}
}
private string _Caption;
/// <summary>
/// Caption of dialog
/// </summary>
public string Caption
{
get
{
return _Caption;
}
}
public CloseState(string caption, int timeout)
{
_Timeout = timeout;
_Caption = caption;
}
}
}
其他消息框
在 C# 中,可以使用 NotifyIcon 类来创建系统托盘图标,并通过弹出消息框来实现新消息提醒
private void Form1_Load(object sender, EventArgs e)
{
// 创建 NotifyIcon 对象
NotifyIcon notifyIcon = new NotifyIcon();
// 设置图标、文本和提示信息
notifyIcon.Icon = new Icon("icon.ico");
notifyIcon.Text = "My App";
notifyIcon.Visible = true;
notifyIcon.ShowBalloonTip(5000, "New Message", "You have a new message!", ToolTipIcon.Info);
}