Search code examples
vb.netfullscreenscreen-resolution

VB.NET ClientSize


I have one form and I want it to be fullscreen, but taskbar should be still visible. And I want it to have one Panel on it, whose borders are 10px away from form borders

I tried hundreds of combinations, and I simply can't achieve this.

here's my code

Public Class Form1

Sub New()

    InitializeComponent()

    WindowState = FormWindowState.Maximized
    Size = New Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)

    Dim p1 As New Panel()
    p1.Location = New Point(10, 10)
    p1.Size = New Size(ClientSize.Width - 20, ClientSize.Height - 20)
    p1.BackColor = Color.Blue

    Controls.Add(p1)

End Sub

End Class

what I want: https://i.sstatic.net/y8sYe.png

what I get: https://i.sstatic.net/lzCKY.png


Solution

  • I would take an entirely different approach where there is no need to calculate anything:

    WindowState = FormWindowState.Maximized
    Size = New Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
    Padding = New Padding(10)
    
    Dim p1 As New Panel()
    p1.Location = New Point(0, 0)
    p1.Dock = DockStyle.Fill
    p1.BackColor = Color.Blue
    
    Controls.Add(p1)
    

    Your calculation is correct for a form that takes entire screen but is not maximized, which you can see by unmaximizing it as soon as it appears. The reason is that you are observing the form sizes from the constructor which is a bit too early (namely, even though you are setting WindowState = FormWindowState.Maximized before everything else, ClientSize still has values corresponding to non-maximized window because the window has not yet been created and shown). If you move your original code to e.g. a Form.Load handler it will give the opposite result - looking correct when the form is maximized and incorrect if not.

    The padding approach works as expected in all cases.