【问题标题】:How do I solve this resize error that makes my form transparent?如何解决使我的表单透明的调整大小错误?
【发布时间】:2020-09-22 14:35:00
【问题描述】:

我有一个代码是一个没有边框的表单,它的大小取决于一个字符串。

就像一个通知表单,

有时表单无法正确调整大小,其中一部分看起来是透明的。

我知道它是透明的,因为透明部分会调用所有事件,例如单击或鼠标滚轮,即使我在其背景上看到程序也是如此。 并检查了表单的 Width 属性及其确定,它大于其显示的部分。

这是表单改变大小的代码,它是改变颜色或大小的唯一方法。

private void ChangeNotification(string Noti, Color C)
{
    string[] Lines = Noti.Split(new[] { '\r', '\n' });
    string Max = "";
    Lines.ToList().ForEach(s =>
    {
        if (s.Length > Max.Length)
            Max = s;
    });
    using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
    {
        SizeF size = graphics.MeasureString(Max, lblInfo.Font);
        Width = (int)size.Width + scroll.Width + 40;
        Height = Lines.Count() * (int)size.Height;
        Top = Screen.PrimaryScreen.WorkingArea.Height - Height;
        Left = Screen.PrimaryScreen.WorkingArea.Width - Width;
    }
    this.BackColor = C;
    lblInfo.Text = Noti;
}

我发送完全相同的文本,有时它会正确更改其大小。

示例失败:

示例确定:

【问题讨论】:

    标签: c# winforms resize transparent


    【解决方案1】:

    只需将标签AutoSize 设置为字符串的内容,然后根据此调整表单的大小。它也适用于多行字符串。为什么要测量?!...

    public void ChangeNotification(string Noti, Color C)
    {
        lblInfo.Text = Noti;
        this.BackColor = C;
        this.Size = new Size(lblInfo.Size.Width + lblInfo.Location.X * 2, lblInfo.Size.Height + lblInfo.Location.Y * 2);
        this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - Width, Screen.PrimaryScreen.WorkingArea.Height - Height);
    }
    

    【讨论】:

    • 谢谢它解决了这个问题。我不知道 AutoSize 也包含新行。
    • 不客气!...如果这解决了您的问题,请接受它作为答案和/或投票。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2023-03-28
    • 2017-07-06
    • 2012-01-01
    相关资源
    最近更新 更多