【问题标题】:maximize windows forms with label size最大化带有标签大小的窗体
【发布时间】:2013-01-12 08:32:29
【问题描述】:

我制作了一个自定义 MessageBox,但在最大化带有标签大小的 msgBox 时遇到了问题。如果我的标签太长太大,那么我希望我的自定义 MessageBox 变大或变小也取决于标签大小。我可以在 Windows 窗体选项中设置它吗?或者我能做什么?

我的代码:

      public static DialogResult Show(string Text, string Caption, string btnOk, string btnCancel)
      {

        MsgBox = new CustomMsgBox();
        MsgBox.label1.Text = Text;
        MsgBox.button1.Text = btnOk;
        MsgBox.button2.Text = btnCancel;
        MsgBox.AutoSize = true;
        result = DialogResult.No;
        MsgBox.ShowDialog();

        return result;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        result = DialogResult.Yes;
        MsgBox.Close();
    }

【问题讨论】:

  • 您需要编写一堆代码来使对话框按比例增长。换句话说,在宽度和高度上都增长。 Winforms 中没有任何东西可以让这一切变得简单,您必须自己解决。并不复杂,只是编写烦人的代码。需要 TextRenderer.MeasureText()。

标签: c# winforms label maximize


【解决方案1】:

您可以在MsgBox_load(object sender, EventArgs e) 中添加以下代码:

private void MsgBox_Load(object sender, EventArgs e)
{
    this.Width = label1.Width + label1.Location.X;
    //do other things you need in the load event.
}

这将根据宽度+label1`的X坐标位置设置MsgBox的width。由于标签可能在也可能不在完整的左侧,这将显示完整的标签并相应地最大化 MsgBox。

【讨论】:

  • 非常感谢,但是我可以用同样的方法来识别标签的高度,然后也改变msgbox吗?
  • 绝对应该是可能的。
  • 我尝试复制粘贴您的代码,但结果仍然相同。我应该把它放在我的代码中的什么地方?根据我上面写的那些代码?
  • MsgBox.cs然后添加加载事件并放置代码
【解决方案2】:

试试这个代码。

在设计师中

  1. 拖放FlowLayoutPanel 控件,根据需要调整流布局宽度
  2. 拖放您的Label 控件

在 .cs 文件中

例如,我在表单加载事件中绑定一些文本并调用调整大小事件

    private void CustMsgBox_Load(object sender, EventArgs e)
    {
        //Binding some long text to the label
        label1.Text = "ga,dsa,bdas,bcc,asbcc,asc,asbc,a c,asc,n asc,baskcas,c sam ckavcmas cmas ckasvmas cmas ckavcma cmaga,dsa,bdas,bcc,asbcc,asc,asbc,a c,asc,n asc,baskcas,c sam ckavcmas cmas ckasvmas cmas ckavcma cmaga,dsa,bdas,bcc,asbcc,asc,asbc,a c,asc,n asc,baskcas,c sam ckavcmas cmas ckasvmas cmas ckavcma cmaga,dsa,bdas,bcc,asbcc,asc,asbc,a c,asc,n asc,baskcas,c sam ckavcmas cmas ckasvmas cmas ckavcma cma";
        this.ResizeWindow(); // Calling this event will resize the label and window
    }

将一些文本绑定到标签后,调用下面的方法

    private void ResizeWindow()
    {
        int iHeight = flowLayoutPanel1.Height;
        flowLayoutPanel1.Height = label1.Height;
        this.Height += (flowLayoutPanel1.Height - iHeight); //This will increase the height of the window accordingly
        this.Top=Convert.ToInt32((Screen.PrimaryScreen.WorkingArea.Height-this.Height)/2); //This will position the window center vertically
    }

【讨论】:

  • 只需将Width 替换为Height。如果对您有帮助,请标记为答案。所以它可能会帮助其他人。
猜你喜欢
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 2012-02-04
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
相关资源
最近更新 更多