gornvix
gornvix

Reputation: 3372

Sizing code in a form resize event does not work

I have a problem sizing a form in a form size event. I am trying to avoid the situation where the form goes off the screen when the user un-maximises the form and the form cannot be resized (as the corner is always off screen). Although I can't now seem to reproduce this situation. Anyway I came up with some code to get out of this situation should it ever occur again. The problem is that the form height does not get set when the form is un-maximized, although the the code in the if statement is reached. One time when I was running my application the Top and Left properties got corrupted and both became -32000. Again I came up some code to prevent this causing a problem. Here is the code, note the width is fixed:

public partial class MainForm : Form
{
    Rectangle sr;
    FormWindowState wp;
    public MainForm()
    {
            sr = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            MaximumSize = new Size(Width, sr.Height);
            wp = WindowState;
    }
    private void MainForm_Activated(object sender, EventArgs e)
    // positions the form
    {
        Top = Properties.Settings.Default.Top;
        if ((Top > sr.Height - 80) || (Top < 0))
             Top = 80;
        Left = Properties.Settings.Default.Left;
        if ((Left > sr.Width - 80) || (Left < 0))
            Left = 80;
        Height = Properties.Settings.Default.Height;
    }
    private void MainForm_Deactivate(object sender, EventArgs e)
    // remembers the forms position
    {
        Properties.Settings.Default.Top = Top;
        Properties.Settings.Default.Left = Left;
        Properties.Settings.Default.Height = Height;
        Properties.Settings.Default.Save();
    }
    private void MainForm_Resize(object sender, EventArgs e)
    {
        Control control = (Control)sender;
        if ((WindowState == FormWindowState.Normal) && 
        (wp == FormWindowState.Maximized) &&
        (control.Size.Height > sr.Height - 80))
            // the following line has no effect: 
            control.Size = new Size(control.Size.Width, 400);
        wp = WindowState;
    }

Thanks.

Upvotes: 1

Views: 322

Answers (1)

athar13
athar13

Reputation: 382

Make sure the Form is not in Maximised state when you are trying to apply the height/width changes.

-- Athar

Upvotes: 1

Related Questions