创建一个无模式消息框

如何创建无模式MessageBox? 我是否必须创建自己的Windows Form类并使用它? 如果是这样,是否有一种简单的方法可以添加警告图标(而不是插入我自己的图像)并根据文本量resize?

您必须创建一个Form并使用Show()将其显示为Modeless。 MessageBox.Show(...)表现出模仿,如ghiboz的例子所示; 显示“消息描述”直到用户按下按钮。

使用MessageBox.Show(...)您可以在消息框关闭后立即获得结果; 使用无模式消息框,当用户最终在消息框中选择某些内容时,您的代码必须具有诸如事件之类的机制才能做出反应。

如果你需要一个消息框,只是在你的代码继续在后台运行时显示自己(该框仍然是模态的,并且会阻止用户使用其他窗口,直到单击OK),你总是可以在自己的线程中启动消息框并继续做你在原始线程中做的事情:

  // Do stuff before. // Start the message box -thread: new Thread(new ThreadStart(delegate { MessageBox.Show ( "Hey user, stuff runs in the background!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning ); })).Start(); // Continue doing stuff while the message box is visible to the user. // The message box thread will end itself when the user clicks OK. 

如果没有编写代码,您可以创建一个在构造函数中执行以下操作的小表单

  • 将参数字符串作为要显示的消息
  • 使用此字符串填写表单上的标签
  • 使用以下之一加载图标(将Enum传递给构造函数)
    • SystemIcons.Application
    • SystemIcons.Asterix
    • SystemIcons.Error
    • SystemIcons.Exclamation
    • SystemIcons.Hand
    • SystemIcons.Information
    • SystemIcons.Question
    • SystemIcons.Shield
    • SystemIcons.Warning
    • SystemIcons.WinLogo
  • 调用Show()将导致它成为modal dialog

如果你真的想要,你可以听到按下OK按钮时触发的事件。

您可以使用SystemIcons使用标准系统警告图标

您必须使用表单并调用showDialog()

并用于图标使用

MessageBoxIcon.Warning

//没有通讯网

 object sync = new object(); ManualResetEvent Wait = new ManualResetEvent(); //you should create a place holder named MessageData for Message Data. List Messages = new List(); internal void ShowMessage(string Test, string Title, ....) { MessageData MSG = new MessageData(Test, Title); Wait.Set(); lock(sync) Messages.Add(MSG); } // another thread should run here. void Private_Show() { while(true) { while(Messsages.Count != 0) { MessageData md; lock(sync) { md = List[0]; List.RemoveAt(0); } MessageBox.Show(md.Text, md.Title, md....); } Wait.WaitOne(); } } 

对于并发消息框,需要更multithreading和更多代码(我没有足够的时间来编写)。

注意:这将创建一个Modal对话框,这不是问题所在

这是一个示例代码

 if (MessageBox.Show("Description of the message", "Caption text", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { // Do some stuff if yes pressed } else { // no pressed }