c# - 根据文本确定自定义消息框的窗口大小

标签 c# .net winforms messagebox text-size

我正在编写一个自定义消息框,其行为应该与 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/

相关文章:

c# - 如何在c#中绘制一个圆角矩形

c# - 为什么 TreeView 控件创建空白节点?

c# - 正则表达式解析 C# 源代码以查找所有字符串

c# - 为什么我不能以相同的方式初始化对象(不使用 ref)?

c# - XStreamingElement 作为 XDocument 的一部分

c# - 如何内部连接来自不同数据上下文的表?

c# - 使用 SQL Server 2008 CLR 进行密码哈希处理

c# - 无法解析引用 Microsoft.Azure.WebJobs.Extensions - 元数据生成失败

c# - MvvmCross: UICollectionView 点击后执行命令

c# - 将数据从 UserControl 传递到另一个