简体   繁体   中英

Move controls in winform on clientsizechanged event C#

I have a windows form where I need to place a header(a string) using the paint event. The header is to be placed in the center. I used the following code:

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);

This works well for me. Now when the user drags the form and changes the client size, the string is no more in center. So I looked for ClientSizeChanged event of Windows forms and tried to repeat the above code. But it doesn't have a PaintEventArgs object, so the last line of the above code, threw an error.

Am I approaching the above mentioned problem (centering the string even if clientsize.width changes) the right way ? If so, how to do it and if not how should I handle the client size change event ?

You should tell your form to Redraw on resize add ResizeRedraw = true; to your form's constructor after InitializeComponent(); .

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

or you can do this manually by adding Invalidate(); to SizeChanged event.

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM