我正在编写一个自定义消息框,其行为应该与 WinForms 中的 MessageBox 类非常相似。除了尝试确定表单的大小(包括显示文本的标签控件)之外,一切都很好。
我不确定如何确定大小,因为涉及许多因素,包括字符串长度、文本中嵌入的空格和换行符以及屏幕大小。
查看 .NET 引用源也没有帮助,因为缩放部分似乎是 native 实现的。
如有任何指点,我们将不胜感激。
最佳答案
您需要确定消息的最大宽度,然后计算出文本换行占用了多少空间。 TextRenderer.MeasureText函数可以为您提供以下信息:
string textMessage = "some really long message..."
int maxWidth = Screen.GetWorkingArea(this).Width - 480;
int useWidth = Math.Min(TextRenderer.MeasureText(textMessage,
Control.DefaultFont).Width, maxWidth);
useWidth = Math.Max(useWidth, 640);
int useHeight = Math.Max(64, TextRenderer.MeasureText(textMessage,
Control.DefaultFont,
new Size(useWidth, 0),
TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak)
.Height);
using (Form f = new Form()) {
f.Text = "Test Message";
f.FormBorderStyle = FormBorderStyle.FixedDialog;
f.MinimizeBox = false;
f.MaximizeBox = false;
f.StartPosition = FormStartPosition.CenterScreen;
f.ClientSize = new Size(useWidth + 8, useHeight + 8);
Label l = new Label { AutoSize = false };
l.Text = textMessage;
l.Font = Control.DefaultFont;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Anchor = AnchorStyles.Left | AnchorStyles.Top |
AnchorStyles.Right | AnchorStyles.Bottom;
l.Location = new Point(4, 4);
l.Size = new Size(f.ClientSize.Width - 8, f.ClientSize.Height - 8);
f.Controls.Add(l);
f.ShowDialog(this);
}
关于c# - 根据文本确定自定义消息框的窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303258/