【问题标题】:Move controls in winform on clientsizechanged event C#在clientsizechanged事件C#上移动winform中的控件
【发布时间】:2014-09-07 01:59:09
【问题描述】:

我有一个 Windows 窗体,我需要在其中使用绘制事件放置一个标题(一个字符串)。标题应放在中心。我使用了以下代码:

string myString="Hello";
Font stringFont = new Font("Arial", 20, FontStyle.Bold);
Size textSize = TextRenderer.MeasureText(myString, stringFont);
int formWidth = (int)(ClientSize.Width - textSize.Width) / 2;
int formHeight = (int)(ClientSize.Height / 35);
e.Graphics.DrawString(measureString, stringFont, System.Drawing.Brushes.DarkBlue, formWidth, formHeight);

这对我很有效。现在,当用户拖动表单并更改客户端大小时,字符串不再位于中心。所以我寻找Windows窗体的ClientSizeChanged事件,并试图重复上面的代码。但是它没有 PaintEventArgs 对象,所以上面代码的最后一行,抛出了一个错误。

我是否以正确的方式解决了上述问题(即使clientsize.width 改变了字符串居中)?如果是这样,该怎么做,如果不是,我应该如何处理客户端大小更改事件?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    您应该告诉您的表单在调整大小时重绘,在 InitializeComponent(); 之后添加 ResizeRedraw = true; 到表单的构造函数。

        public Form1()
        {
            InitializeComponent();
            ResizeRedraw = true;
        }
    

    或者您可以通过将Invalidate(); 添加到SizeChanged 事件来手动执行此操作。

        public Form1()
        {
            InitializeComponent();
            SizeChanged += Form1_SizeChanged;
        }
    
        void Form1_SizeChanged(object sender, EventArgs e)
        {
            Invalidate();
        }
    
    
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);
    
            string myString = "Hello";
            Font stringFont = new Font("Arial", 20, FontStyle.Bold);
            Size textSize = TextRenderer.MeasureText(myString, stringFont);
            int formWidth = (int)(Size.Width - textSize.Width) / 2;
            int formHeight = (int)(Size.Height / 35);
            e.Graphics.DrawString(myString, stringFont, System.Drawing.Brushes.DarkBlue, formWidth, formHeight);
            e.Graphics.Flush();
        }
    

    【讨论】:

    • 完美运行。非常感谢:)
    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2016-03-20
    • 2011-12-30
    • 2018-07-16
    相关资源
    最近更新 更多