自定义MessageBox自动换行需求:无需修改消息实现完整显示
解决自定义MessageBox自动换行及内容截断问题
核心解决方案:通过控件属性配置+动态尺寸调整实现自动换行
不需要修改每条消息内容,只需调整Label控件的属性,并在代码中动态计算文本所需的显示空间即可:
1. 配置lblMsg控件的关键属性
可以直接在WinForms设计器中设置,也可以在代码里初始化:
- 设置
WordWrap = true:开启文本自动换行功能 - 设置
AutoSize = false:关闭控件自动大小,让我们可以控制其显示范围 - 设置
Dock = DockStyle.Fill:让Label填充窗体内部除图标外的空间(或手动调整Size和Padding,避免文本贴边) - 设置
TextAlign为合适的对齐方式(比如ContentAlignment.MiddleLeft)
2. 动态计算文本高度,调整窗体尺寸
在设置消息文本后,计算文本所需的显示高度,同步调整Label和整个Alert窗体的大小,避免内容截断:
3. 重新计算窗体位置
因为窗体高度可能变化,需要重新计算右下角的显示位置,避免超出屏幕工作区
修改后的完整代码
public void showAlert(string msg, enmType type) { this.Opacity = 0.0; this.StartPosition = FormStartPosition.Manual; string fname; int alertIndex = 1; // 找到可用的alert窗体编号 for (; alertIndex < 10; alertIndex++) { fname = "alert" + alertIndex.ToString(); Form_Alert frm = (Form_Alert)Application.OpenForms[fname]; if (frm == null) { this.Name = fname; break; } } // 设置消息类型对应的图标和背景色 switch(type) { case enmType.Success: this.pictureBox1.Image = Resources.success; this.BackColor = Color.SeaGreen; break; case enmType.Error: this.pictureBox1.Image = Resources.error; this.BackColor = Color.DarkRed; break; case enmType.Info: this.pictureBox1.Image = Resources.info; this.BackColor = Color.RoyalBlue; break; case enmType.Warning: this.pictureBox1.Image = Resources.warning; this.BackColor = Color.DarkOrange; break; } // 配置Label的自动换行属性(如果未在设计器设置) lblMsg.WordWrap = true; lblMsg.AutoSize = false; lblMsg.Dock = DockStyle.Fill; lblMsg.Padding = new Padding(10, 5, 10, 5); // 设置内边距避免文本贴边 // 设置消息文本 lblMsg.Text = msg; // 计算文本所需高度,调整Label和窗体尺寸 using (Graphics g = lblMsg.CreateGraphics()) { SizeF textSize = g.MeasureString(msg, lblMsg.Font, lblMsg.Width); int requiredLabelHeight = (int)Math.Ceiling(textSize.Height); lblMsg.Height = requiredLabelHeight; // 调整窗体高度:图标高度 + Label高度 + 上下间距(可根据实际布局调整) this.Height = pictureBox1.Height + requiredLabelHeight + 15; } // 重新计算右下角位置,避免超出屏幕 this.x = Screen.PrimaryScreen.WorkingArea.Width - this.Width - 5; this.y = Screen.PrimaryScreen.WorkingArea.Height - this.Height * alertIndex - 5 * alertIndex; this.Location = new Point(this.x, this.y); this.Show(); this.action = enmAction.start; this.timer1.Interval = 1; this.timer1.Start(); }
内容的提问来源于stack exchange,提问作者Laffont Magalie
相关产品推荐
相关产品推荐

