这个主题在其他SO问题中已经充分涵盖,但由于这个特定的问题有几个关于使用UI自动化/窗口查找技术(我不是特别喜欢)和创建自己的对话框而没有提供代码的通用建议,因此我决定发布自己的解决方案。可以创建一个可实例化的MessageBox
类,如下所示:
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace Common
public static DialogResult Show(IWin32Window owner, string message, string title = null, MessageBoxButtons? buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information)
public static DialogResult Show(string message, string title = null, MessageBoxButtons? buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information)
public static MsgBox Create(string message, string title = null, MessageBoxButtons? buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information)
void Init(string message, string title, MessageBoxButtons? buttons, MessageBoxIcon icon)
void InitButtons(MessageBoxButtons? buttons)
}
void InitIcon(MessageBoxIcon icon)
_picIcon.Width = _picIcon.Image.Width;
_picIcon.Height = _picIcon.Image.Height;
}
private void ButtonClick(object sender, EventArgs e)
Close();
}
private static Size MessageSize(string message)
}
else
") select m.Value).ToArray();
int lines = groups.Length+1;
width = 700;
height += (int)(size.Height+10) * lines;
}
return new Size(width, height);
}
private void AddButton(string caption)
}
}
可以将对话框的引用保存在类作用域中,显示对话框并获取结果,或者在应用程序退出事件处理程序中关闭对话框。
MsgBox _msgBox;
void eventHandler1(object sender, EventArgs e)
{
_msgBox = MsgBox.Create("Do you want to continue", "Inquiry", MessageBoxButtons.YesNo);
var result = _msgBox.ShowDialog();
}
void applicationExitHandler(object sender, EventArgs e)
{
if (_msgBox != null)
_msgBox.Close();
}
MessageBox.Show(...)
是模态的,那么程序怎么能发送一个键呢?你是使用线程/任务吗? - Fischermaen