Windows form окно на весь экран

I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode). Currently I am setting FormBorderStyle to None and WindowState to Maximized which gives...

I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode).

Currently I am setting FormBorderStyle to None and WindowState to Maximized which gives me a little more space, but it doesn’t cover over the taskbar if it is visible.

What do I need to do to use that space as well?

For bonus points, is there something I can do to make my MenuStrip autohide to give up that space as well?

Divins Mathew's user avatar

asked Feb 2, 2009 at 22:10

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

answered Feb 3, 2009 at 15:30

H H's user avatar

H HH H

258k30 gold badges323 silver badges508 bronze badges

5

A tested and simple solution

I’ve been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn’t work correctly, so after a lot code testing I solved this puzzle.

Note: I’m using Windows 8 and my taskbar isn’t on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the «full screen mode» and the second leaves the «full screen mode». So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I’m not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

Community's user avatar

answered May 26, 2013 at 22:59

Zignd's user avatar

ZigndZignd

6,75611 gold badges38 silver badges61 bronze badges

3

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

Vishal Suthar's user avatar

answered Feb 2, 2009 at 23:28

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. («TopMost» means the window stays on top of other windows, unless they are also marked «TopMost».)

ToolmakerSteve's user avatar

answered Feb 12, 2013 at 12:43

Raghavendra Devraj's user avatar

I worked on Zingd idea and made it simpler to use.

I also added the standard F11 key to toggle fullscreen mode.

Setup

Everything is now in the FullScreen class, so you don’t have to declare a bunch of variables in your Form. You just instanciate a FullScreen object in your form’s constructor :

FullScreen fullScreen;

public Form1()
{
    InitializeComponent();
    fullScreen = new FullScreen(this);
}

Please note this assumes the form is not maximized when you create the FullScreen object.

Usage

You just use one of the classe’s functions to toggle the fullscreen mode :

fullScreen.Toggle();

or if you need to handle it explicitly :

fullScreen.Enter();
fullScreen.Leave();

Code

using System.Windows.Forms;


class FullScreen
{ 
    Form TargetForm;

    FormWindowState PreviousWindowState;

    public FullScreen(Form targetForm)
    {
        TargetForm = targetForm;
        TargetForm.KeyPreview = true;
        TargetForm.KeyDown += TargetForm_KeyDown;
    }

    private void TargetForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.F11)
        {
            Toggle();
        }
    }

    public void Toggle()
    {
        if (TargetForm.WindowState == FormWindowState.Maximized)
        {
            Leave();
        }
        else
        {
            Enter();
        }
    }
        
    public void Enter()
    {
        if (TargetForm.WindowState != FormWindowState.Maximized)
        {
            PreviousWindowState = TargetForm.WindowState;
            TargetForm.WindowState = FormWindowState.Normal;
            TargetForm.FormBorderStyle = FormBorderStyle.None;
            TargetForm.WindowState = FormWindowState.Maximized;
        }
    }
      
    public void Leave()
    {
        TargetForm.FormBorderStyle = FormBorderStyle.Sizable;
        TargetForm.WindowState = PreviousWindowState;
    }
}

answered Jun 24, 2020 at 9:12

geriwald's user avatar

geriwaldgeriwald

1921 gold badge3 silver badges17 bronze badges

I recently made a Mediaplayer application and I used API calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had the focus or was exited.

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer

Sub HideTrayBar()
    Try


        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(tWnd, 0)
        ShowWindow(bWnd, 0)
    Catch ex As Exception
        'Error hiding the taskbar, do what you want here..'
    End Try
End Sub
Sub ShowTraybar()
    Try
        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(bWnd, 1)
        ShowWindow(tWnd, 1)
    Catch ex As Exception
        'Error showing the taskbar, do what you want here..'
    End Try


End Sub

Tridib Roy Arjo's user avatar

answered Feb 2, 2009 at 23:19

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

3

You need to set your window to be topmost.

answered Feb 2, 2009 at 22:12

Tron's user avatar

TronTron

1,38710 silver badges11 bronze badges

2

I don’t know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Your_Form_Name : Form
{
    public Your_Form_Name()
    {
        InitializeComponent();
    }

    // CODE STARTS HERE

    private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
    private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
    private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
    private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
    private bool fullscreen = false;
    /// <summary>
    /// Goes to fullscreen or the old state.
    /// </summary>
    private void UpgradeFullscreen()
    {
        if (!fullscreen)
        {
            oldsize = this.Size;
            oldstate = this.WindowState;
            oldstyle = this.FormBorderStyle;
            oldlocation = this.Location;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            fullscreen = true;
        }
        else
        {
            this.Location = oldlocation;
            this.WindowState = oldstate;
            this.FormBorderStyle = oldstyle;
            this.Size = oldsize;
            fullscreen = false;
        }
    }

    // CODE ENDS HERE
}

Usage:

UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.

Notice:
You MUST place it inside your Form’s class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don’t place it on any form, code this will create an exception.

answered Oct 28, 2016 at 14:12

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

answered May 16, 2019 at 19:28

Segan's user avatar

SeganSegan

4765 silver badges5 bronze badges

If you want to keep the border of the form and have it cover the task bar, use the following:

Set FormBoarderStyle to either FixedSingle or Fixed3D

Set MaximizeBox to False

Set WindowState to Maximized

answered Jun 9, 2021 at 13:48

Quinton's user avatar

I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode).

Currently I am setting FormBorderStyle to None and WindowState to Maximized which gives me a little more space, but it doesn’t cover over the taskbar if it is visible.

What do I need to do to use that space as well?

For bonus points, is there something I can do to make my MenuStrip autohide to give up that space as well?

Divins Mathew's user avatar

asked Feb 2, 2009 at 22:10

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

answered Feb 3, 2009 at 15:30

H H's user avatar

H HH H

258k30 gold badges323 silver badges508 bronze badges

5

A tested and simple solution

I’ve been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn’t work correctly, so after a lot code testing I solved this puzzle.

Note: I’m using Windows 8 and my taskbar isn’t on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the «full screen mode» and the second leaves the «full screen mode». So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I’m not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

Community's user avatar

answered May 26, 2013 at 22:59

Zignd's user avatar

ZigndZignd

6,75611 gold badges38 silver badges61 bronze badges

3

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

Vishal Suthar's user avatar

answered Feb 2, 2009 at 23:28

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. («TopMost» means the window stays on top of other windows, unless they are also marked «TopMost».)

ToolmakerSteve's user avatar

answered Feb 12, 2013 at 12:43

Raghavendra Devraj's user avatar

I worked on Zingd idea and made it simpler to use.

I also added the standard F11 key to toggle fullscreen mode.

Setup

Everything is now in the FullScreen class, so you don’t have to declare a bunch of variables in your Form. You just instanciate a FullScreen object in your form’s constructor :

FullScreen fullScreen;

public Form1()
{
    InitializeComponent();
    fullScreen = new FullScreen(this);
}

Please note this assumes the form is not maximized when you create the FullScreen object.

Usage

You just use one of the classe’s functions to toggle the fullscreen mode :

fullScreen.Toggle();

or if you need to handle it explicitly :

fullScreen.Enter();
fullScreen.Leave();

Code

using System.Windows.Forms;


class FullScreen
{ 
    Form TargetForm;

    FormWindowState PreviousWindowState;

    public FullScreen(Form targetForm)
    {
        TargetForm = targetForm;
        TargetForm.KeyPreview = true;
        TargetForm.KeyDown += TargetForm_KeyDown;
    }

    private void TargetForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.F11)
        {
            Toggle();
        }
    }

    public void Toggle()
    {
        if (TargetForm.WindowState == FormWindowState.Maximized)
        {
            Leave();
        }
        else
        {
            Enter();
        }
    }
        
    public void Enter()
    {
        if (TargetForm.WindowState != FormWindowState.Maximized)
        {
            PreviousWindowState = TargetForm.WindowState;
            TargetForm.WindowState = FormWindowState.Normal;
            TargetForm.FormBorderStyle = FormBorderStyle.None;
            TargetForm.WindowState = FormWindowState.Maximized;
        }
    }
      
    public void Leave()
    {
        TargetForm.FormBorderStyle = FormBorderStyle.Sizable;
        TargetForm.WindowState = PreviousWindowState;
    }
}

answered Jun 24, 2020 at 9:12

geriwald's user avatar

geriwaldgeriwald

1921 gold badge3 silver badges17 bronze badges

I recently made a Mediaplayer application and I used API calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had the focus or was exited.

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer

Sub HideTrayBar()
    Try


        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(tWnd, 0)
        ShowWindow(bWnd, 0)
    Catch ex As Exception
        'Error hiding the taskbar, do what you want here..'
    End Try
End Sub
Sub ShowTraybar()
    Try
        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(bWnd, 1)
        ShowWindow(tWnd, 1)
    Catch ex As Exception
        'Error showing the taskbar, do what you want here..'
    End Try


End Sub

Tridib Roy Arjo's user avatar

answered Feb 2, 2009 at 23:19

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

3

You need to set your window to be topmost.

answered Feb 2, 2009 at 22:12

Tron's user avatar

TronTron

1,38710 silver badges11 bronze badges

2

I don’t know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Your_Form_Name : Form
{
    public Your_Form_Name()
    {
        InitializeComponent();
    }

    // CODE STARTS HERE

    private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
    private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
    private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
    private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
    private bool fullscreen = false;
    /// <summary>
    /// Goes to fullscreen or the old state.
    /// </summary>
    private void UpgradeFullscreen()
    {
        if (!fullscreen)
        {
            oldsize = this.Size;
            oldstate = this.WindowState;
            oldstyle = this.FormBorderStyle;
            oldlocation = this.Location;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            fullscreen = true;
        }
        else
        {
            this.Location = oldlocation;
            this.WindowState = oldstate;
            this.FormBorderStyle = oldstyle;
            this.Size = oldsize;
            fullscreen = false;
        }
    }

    // CODE ENDS HERE
}

Usage:

UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.

Notice:
You MUST place it inside your Form’s class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don’t place it on any form, code this will create an exception.

answered Oct 28, 2016 at 14:12

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

answered May 16, 2019 at 19:28

Segan's user avatar

SeganSegan

4765 silver badges5 bronze badges

If you want to keep the border of the form and have it cover the task bar, use the following:

Set FormBoarderStyle to either FixedSingle or Fixed3D

Set MaximizeBox to False

Set WindowState to Maximized

answered Jun 9, 2021 at 13:48

Quinton's user avatar

I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode).

Currently I am setting FormBorderStyle to None and WindowState to Maximized which gives me a little more space, but it doesn’t cover over the taskbar if it is visible.

What do I need to do to use that space as well?

For bonus points, is there something I can do to make my MenuStrip autohide to give up that space as well?

Divins Mathew's user avatar

asked Feb 2, 2009 at 22:10

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

answered Feb 3, 2009 at 15:30

H H's user avatar

H HH H

258k30 gold badges323 silver badges508 bronze badges

5

A tested and simple solution

I’ve been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn’t work correctly, so after a lot code testing I solved this puzzle.

Note: I’m using Windows 8 and my taskbar isn’t on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the «full screen mode» and the second leaves the «full screen mode». So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I’m not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

Community's user avatar

answered May 26, 2013 at 22:59

Zignd's user avatar

ZigndZignd

6,75611 gold badges38 silver badges61 bronze badges

3

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

Vishal Suthar's user avatar

answered Feb 2, 2009 at 23:28

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. («TopMost» means the window stays on top of other windows, unless they are also marked «TopMost».)

ToolmakerSteve's user avatar

answered Feb 12, 2013 at 12:43

Raghavendra Devraj's user avatar

I worked on Zingd idea and made it simpler to use.

I also added the standard F11 key to toggle fullscreen mode.

Setup

Everything is now in the FullScreen class, so you don’t have to declare a bunch of variables in your Form. You just instanciate a FullScreen object in your form’s constructor :

FullScreen fullScreen;

public Form1()
{
    InitializeComponent();
    fullScreen = new FullScreen(this);
}

Please note this assumes the form is not maximized when you create the FullScreen object.

Usage

You just use one of the classe’s functions to toggle the fullscreen mode :

fullScreen.Toggle();

or if you need to handle it explicitly :

fullScreen.Enter();
fullScreen.Leave();

Code

using System.Windows.Forms;


class FullScreen
{ 
    Form TargetForm;

    FormWindowState PreviousWindowState;

    public FullScreen(Form targetForm)
    {
        TargetForm = targetForm;
        TargetForm.KeyPreview = true;
        TargetForm.KeyDown += TargetForm_KeyDown;
    }

    private void TargetForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.F11)
        {
            Toggle();
        }
    }

    public void Toggle()
    {
        if (TargetForm.WindowState == FormWindowState.Maximized)
        {
            Leave();
        }
        else
        {
            Enter();
        }
    }
        
    public void Enter()
    {
        if (TargetForm.WindowState != FormWindowState.Maximized)
        {
            PreviousWindowState = TargetForm.WindowState;
            TargetForm.WindowState = FormWindowState.Normal;
            TargetForm.FormBorderStyle = FormBorderStyle.None;
            TargetForm.WindowState = FormWindowState.Maximized;
        }
    }
      
    public void Leave()
    {
        TargetForm.FormBorderStyle = FormBorderStyle.Sizable;
        TargetForm.WindowState = PreviousWindowState;
    }
}

answered Jun 24, 2020 at 9:12

geriwald's user avatar

geriwaldgeriwald

1921 gold badge3 silver badges17 bronze badges

I recently made a Mediaplayer application and I used API calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had the focus or was exited.

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer

Sub HideTrayBar()
    Try


        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(tWnd, 0)
        ShowWindow(bWnd, 0)
    Catch ex As Exception
        'Error hiding the taskbar, do what you want here..'
    End Try
End Sub
Sub ShowTraybar()
    Try
        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(bWnd, 1)
        ShowWindow(tWnd, 1)
    Catch ex As Exception
        'Error showing the taskbar, do what you want here..'
    End Try


End Sub

Tridib Roy Arjo's user avatar

answered Feb 2, 2009 at 23:19

Stefan's user avatar

StefanStefan

11.4k7 gold badges50 silver badges75 bronze badges

3

You need to set your window to be topmost.

answered Feb 2, 2009 at 22:12

Tron's user avatar

TronTron

1,38710 silver badges11 bronze badges

2

I don’t know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Your_Form_Name : Form
{
    public Your_Form_Name()
    {
        InitializeComponent();
    }

    // CODE STARTS HERE

    private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
    private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
    private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
    private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
    private bool fullscreen = false;
    /// <summary>
    /// Goes to fullscreen or the old state.
    /// </summary>
    private void UpgradeFullscreen()
    {
        if (!fullscreen)
        {
            oldsize = this.Size;
            oldstate = this.WindowState;
            oldstyle = this.FormBorderStyle;
            oldlocation = this.Location;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            fullscreen = true;
        }
        else
        {
            this.Location = oldlocation;
            this.WindowState = oldstate;
            this.FormBorderStyle = oldstyle;
            this.Size = oldsize;
            fullscreen = false;
        }
    }

    // CODE ENDS HERE
}

Usage:

UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.

Notice:
You MUST place it inside your Form’s class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don’t place it on any form, code this will create an exception.

answered Oct 28, 2016 at 14:12

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

answered May 16, 2019 at 19:28

Segan's user avatar

SeganSegan

4765 silver badges5 bronze badges

If you want to keep the border of the form and have it cover the task bar, use the following:

Set FormBoarderStyle to either FixedSingle or Fixed3D

Set MaximizeBox to False

Set WindowState to Maximized

answered Jun 9, 2021 at 13:48

Quinton's user avatar

0 / 0 / 0

Регистрация: 12.03.2012

Сообщений: 46

1

Как развернуть форму на весь экран

14.04.2012, 09:11. Показов 84506. Ответов 6


Подскажите пожалуйста — как программно максимизировать форму? Могу программно установить произвольные размеры формы, могу узнав разрешение экрана, растянуть форму на весь экран, а мне надо именно максимизировать форму — оказывается это ни одно и тоже, что растянуть форму на весь экран…

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



DimanRu

717 / 708 / 168

Регистрация: 15.06.2011

Сообщений: 1,704

14.04.2012, 09:27

2

Ну вот так:

C#
1
this.WindowState = FormWindowState.Maximized;



7



0 / 0 / 0

Регистрация: 12.03.2012

Сообщений: 46

14.04.2012, 09:46

 [ТС]

3

Большое спасибо… это именно то, что я хотел.



0



2 / 2 / 1

Регистрация: 15.09.2012

Сообщений: 47

27.09.2013, 12:16

4

А существует ли способ разворачивания полностью на весь экран, как видео или игры?



0



154 / 153 / 29

Регистрация: 21.05.2010

Сообщений: 338

27.09.2013, 13:28

5

bezoomec, в WPF



0



208 / 164 / 29

Регистрация: 11.09.2013

Сообщений: 445

28.09.2013, 17:23

6

комбинируйте windowstate с BorderStyle = BorderStyles.None;



2



Teminkasky

0 / 0 / 0

Регистрация: 06.11.2018

Сообщений: 34

12.07.2019, 16:51

7

Цитата
Сообщение от DimanRu
Посмотреть сообщение

Ну вот так:

C#
1
this.WindowState = FormWindowState.Maximized;

Спасибо, очень помогли!



0



Как сделать отображение Windows Forms/WPF приложения на полный экран без рамки?


  • Вопрос задан

    более трёх лет назад

  • 14820 просмотров

Для Windows Forms:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;

Пригласить эксперта

Зачем еще лишний код строчить.А не проще в Студии в свойствах окна все выставить???


  • Показать ещё
    Загружается…

05 февр. 2023, в 11:27

15000 руб./за проект

05 февр. 2023, в 11:25

4000 руб./за проект

05 февр. 2023, в 11:16

500 руб./в час

Минуточку внимания

Проверенное и простое решение

Я искал ответ на этот вопрос в SO и некоторых других сайтах, но один ответ был для меня очень сложным, а некоторые другие ответы просто не работают правильно, поэтому после большого тестирования кода я решил эту головоломку.

Примечание: я использую Windows 8 и моя панель задач не находится в режиме автоматического скрытия.

Я обнаружил, что установка WindowState на Normal перед выполнением каких-либо изменений остановит ошибку с непокрытой панелью задач.

Код

Я создал этот класс с двумя методами, первый входит в «полноэкранный режим», а второй выходит из «полноэкранного режима». Итак, вам просто нужно создать объект этого класса и передать форму, которую вы хотите установить в полноэкранном режиме, в качестве аргумента методу EnterFullScreenMode или методу LeaveFullScreenMode:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Пример использования

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

Я поместил тот же ответ на другой вопрос, и я не уверен, является ли он дубликатом или нет. (Ссылка на другой вопрос: Как отобразить форму Windows в полноэкранном режиме поверх панели задач?)

Блоговая публикация пользователя: KinsT Эта публикация была перенесена из личного блога пользователя в общие разделы уровок сайта.

Для изучения данного материала понадобится знать следующее:

  1. Инициализация библиотеки Tao OpenGL на языке C# в среде .NET
  2. Подробное описание инициализации и визуализации в OpenGL на языке C#

В принципе, переход в полноэкранный режим (далее ПР ;) — задача довольно простая, но требует значительных затрат по времени при написании кода. Однако, один раз написав код, вы можете без труда использовать его во всех OpenGL приложениях.
Нужно сказать сразу, что полная инициализация П� через WinApi здесь рассматриваться не будет, иначе зачем тогда использовать С# и .Net-обвертки типа ТАО? Также нужно отметить, что сам по себе С# дает падение производительности при обработке графики примерно на 15%.

И наконец, по небольшому, но собственному опыту скажу, что работать с графикой в родном С++ все-таки удобней.
Весь процесс создания полноэкранного режима разобьем на две части:

  1. Создание оконного масштабируемого приложения
  2. «Простая инициализация» полноэкранного режима

Создание оконного масштабируемого приложения

Подготовка оконного масштабируемого приложения

Для начала создаем проект Windows Forms и дадим ему название TAO_Fullscreen_Mode. Точно так же, как и в уроке «Инициализация библиотеки Tao OpenGL на языке C# в среде .NET», добавляем ссылки (Links) на библиотеки Tao.OpenGL.dll, Tao.FreeGlut.dll, Tao.Platform.Windows.dll.

Главное окно программы переименуем из Form1 в FormFS, параметр Name в свойствах окна (рис. 1).

Дадим ему название TAO Fullscreen Form (параметр Text). Наше приложение будет использовать реакции нажатия клавиш. Для того, чтобы включить обработчик событий нажатия клавиш, необходимо в свойствах формы для параметра KeyPreview выставить значение True (рис. 1).

Таким образом, когда наше окно имеет фокус (выделено в настоящий момент) будут обрабатываться события нажатия клавиш клавиатуры.
Уроки OpenGL различных тематик: KeyPreview Рисунок 1. KeyPreview.

Необходимо также поместить на форму элемент управления SimpleOpenGlControl. В свойствах элемента нужно изменить параметр Dock на значение Fill (окно примет вид, как показано на рисунке 2) и переименовать его в TaoWin.
Уроки OpenGL различных тематик: изменения параметра Dock на значение Fill Рисунок 2. Изменения параметра Dock на значение Fill.
Теперь можно отложить мышку в сторону и перейти непосредственно к написанию кода. Для работы с импортированными библиотеками, необходимо включить соответствующие пространства имен:

Листинг 1:

Код:

/*http://esate.ru, KinsT*/

using System;
using System.Drawing;
using System.Windows.Forms;
// Библиотеки для работы с графикой;
using Tao.OpenGl;
using Tao.Platform.Windows;
using Tao.FreeGlut;

Используя директивы #region и #endregion, выделите блок кода внутри класса FormFS и дайте этому блоку название «+++ GLOBAL +++». Сейчас Ваш код должен выглядеть, как показано в Листинге 2:

Листинг 2:

Код:

/*http://esate.ru, KinsT*/

namespace TAO_Fullscreen_Mode
{
    public partial class FormFS : Form
    {
        #region +++ GLOBAL +++
        
        #endregion

        public FormFS()
        {
            InitializeComponent();
        }
    }
} 

Создадим переменную FS типа bool внутри блока GLOBAL, чтобы она была видна во всех функциях-методах данного класса. Переменная FS является флагом указывающим, какой из режимов полноэкранный или оконный выбран для работы приложения в данный момент.

Необходимо также добавить еще один конструктор класса с параметром (вообще говоря, можно просто изменить стандартный, но этика программирования мне подсказывает, что от стандартных конструкторов без параметров при написании кода лучше не отказываться). В качестве параметра конструктора будем использовать переменную типа bool с названием fullscreen. В каждом конструкторе инициализируем работу элемента TaoWin.

Листинг 3:

Код:

/*http://esate.ru, KinsT*/

namespace TAO_Fullscreen_Mode
{
    public partial class FormFS : Form
    {
        #region +++ GLOBAL +++
        // Флаг полноэкранного режима;
        private bool FS;
        #endregion

        public FormFS()
        {
            InitializeComponent();
            // Инициализируем работу TaoWin;
            TaoWin.InitializeContexts();
        }
        public FormFS(bool fullscreen)
        {
            InitializeComponent();
       // Инициализируем работу TaoWin;
            TaoWin.InitializeContexts();
        }
    }
} 

Таким образом, конструктор с параметром будет определять в каком режиме запустить приложение, а стандартный конструктор без параметра по-умолчанию запустит приложение в оконном режиме.

Создайте функцию private void InitGL() в которой будем проводить инициализацию OpenGL. Все настройки, которые касаются OpenGL-сцены, расположены именно в этой функции:

Листинг 4:

Код:

/*http://esate.ru, KinsT*/

        // Инициализация OpenGL
        private void InitGL()
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_RGBA |
                Glut.GLUT_DEPTH |
                Glut.GLUT_DOUBLE);
            // Разрешить плавное цветовое сглаживание;
            Gl.glShadeModel(Gl.GL_SMOOTH);
            // Разрешить тест глубины;
            Gl.glEnable(Gl.GL_DEPTH_TEST);
            // Разрешить очистку буфера глубины;
            Gl.glClearDepth(1.0f);
            // Определение типа теста глубины;
            Gl.glDepthFunc(Gl.GL_LEQUAL);
            // Слегка улучшим вывод перспективы;
            Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST);
            // Разрешаем смешивание;
            Gl.glEnable(Gl.GL_BLEND);
            // Устанавливаем тип смешивания;
            Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
        }

В функции glutInitDisplayMode(…) мы инициализировали двойной буфер кадра, буфер глубины и режим отображения цветов GLUT_RGBA — для вывода цвета будет использовано три компоненты цвета + альфа канал прозрачности. Использование такой модели цветов дает возможность в дальнейшем использовать смешивание и использовать по выбору различные режимы сглаживания (точек, линий, полигонов).

Последние три функции кода рассмотрим подробнее:

  • Gl.glHint (target, mode) – управляет способом выполнения растеризации примитивов и может принимать различные параметры. Так в качестве target могут выступать следующие:
    • GL_FOG_HINT — точность вычислений при наложении тумана;
    • GL_LINE_SMOOTH_HINT — управление качеством прямых;
    • GL_PERSPECTIVE_CORRECTION_HINT — точность интерполяции координат при вычислении цветов и наложении текстуры;
    • GL_POINT_SMOOTH_HINT — управление качеством точек;
    • при значении параметра mode равном GL_NICEST точки рисуются как окружности;
    • GL_POLYGON_SMOOTH_HINT — управление качеством вывода сторон многоугольника.
    • В качестве параметра mode выступают такие параметры:

    • GL_FASTEST — используется наиболее быстрый алгоритм рисования;
    • GL_NICEST — используется алгоритм, обеспечивающий лучшее качество;
    • GL_DONT_CARE — выбор алгоритма зависит от реализации;

  • Gl.glEnable(Gl.GL_BLEND) – разрешаем смешивание. Эту функцию необходимо вызывать, если в дальнейшем вы планируете, к примеру, наслаивать друг на друга слои с различной степенью прозрачности;
  • Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA) – выбираем наиболее подходящие параметры смешивания.

Далее необходимо создать функцию изменения размеров окна OpenGL (сцены) private void ResizeGlScene(). Эта функция должна быть вызвана всякий раз, когда мы хотим изменить размеры сцены. Например, при растягивании окна мышью, когда мы находимся в оконном режиме. Также эта функция должна быть вызвана хотя бы один раз при инициализации ПР, чтобы установить размеры области вывода и настроить нашу сцену перед отрисовкой.

Размер сцены устанавливается в зависимости от текущих размеров элемента TaoWin, это как раз одно из свойств, благодаря которому можно упростить себе работу при инициализации ПР.

Листинг 5:

Код:

/*http://esate.ru, KinsT*/

        // Изменение размеров окна OpenGL
        void ResizeGlScene()
        {
            // Предупредим деление на нуль;
            if (TaoWin.Height == 0)
            {
                TaoWin.Height = 1;
            }
            // Сбрасываем текущую область просмотра;
            Gl.glViewport(0, 0, TaoWin.Width, TaoWin.Height);
            // Выбираем матрицу проекций;
            Gl.glMatrixMode(Gl.GL_PROJECTION);
            // Сбрасываем выбранную матрицу;
            Gl.glLoadIdentity();
            // Вычисляем новые геометрические размеры сцены;
            Glu.gluPerspective(45.0f, 
                (float)TaoWin.Width / (float)TaoWin.Height, 
                0.1f, 100.0f);
            // Выбираем матрицу вида модели;
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            // Сбрасываем ее;
            Gl.glLoadIdentity();
        } 

Хотелось бы отметить следующее, что при вызове функции gluPerspective и задании ее параметров нужно быть внимательным, хотя в определении функции и написано, что параметры имеют тип double, но лучше приводить все параметры к типу float. Ниже приведу описание каждого параметра функции:

Функция gluPerspective — устанавливает матрицу перспективной проекции.

void gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); fovy — область угла просмотра по вертикали в градусах;

aspect — (ширина области просмотра)/(высота области просмотра). Очень важный параметр, если не привести его к типу float, то вместо шарика Вы обязательно получите яйцо.

zNear — расстояние до ближней плоскости отсечения (всё что ближе — не рисуется);

zFar — расстояние до дальней плоскости отсечения (всё что дальше — не рисуется).

Теперь, когда Вы имеете все функции необходимые для инициализации сцены, нужно создать функцию, которая будет подготавливать все, что Вы захотите нарисовать. Назовем ее private void DrawGlScene(), код данной функции приведен в Листинге 6:

Листинг 6:

Код:

/*http://esate.ru, KinsT*/

//РИСОВАНИЕ СЦЕНЫ
        private void DrawGlScene()
        {
            // Выбираем цвет очистки экрана;
            Gl.glClearColor(0.0f, 0.8f, 0.0f, 1.0f);
            // Очищаем экран выбранным цветом;
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
            // Сбрасываем текущую матрицу проекций;
            Gl.glLoadIdentity();
            // Обязательно нужно сместиться по оси Z,
            // иначе ни чего не будет видно;
            Gl.glTranslatef(0, 0, -3.0f);

            Gl.glPushMatrix();
            // Здесь можно рисовать что угодно :)
            Gl.glPopMatrix();

            Gl.glFlush();
            TaoWin.Invalidate();
        }

Для запуска приложения необходимо, во-первых, провести инициализацию OpenGL-сцены с помощью подготовленных ранее функций, а во-вторых, добавить обработчик события происходящего при изменении размеров окна. Не будем останавливаться и проведем инициализацию OpenGL, для этого добавим вызов функций InitGL(), ResizeGlScene() и DrawGlScene() в конструкторы класса FormFS. Причем последовательность вызова функций в этом случае имеет большое значение!

Листинг 7:

Код:

/*http://esate.ru, KinsT*/

#region CONSTRUCTORS
        public FormFS()
        {
            InitializeComponent();
            // Инициализируем работу TaoWin;
            TaoWin.InitializeContexts();
            // Инициализация OpenGL
            // !!!Последовательность строк имеет значение!!!
            InitGL();
            ResizeGlScene();
            DrawGlScene();
        }

        public FormFS(bool fullscreen)
        {
            InitializeComponent();
            // Инициализируем работу TaoWin;
            TaoWin.InitializeContexts();
            // Инициализация OpenGL
            // !!!Последовательность строк имеет значение!!!
            InitGL();
            ResizeGlScene();
            DrawGlScene();
        }
#endregion

Теперь настало время вспомнить о мышке! Перейдите к конструктору формы и выделите мышью форму FormFS. Далее зайдите в «Свойства», далее в «События» (Events;), кнопка с желтой молнией (рис.3). Выберите свойство Resize и нажмите двойным кликом на белом поле. После этого студия сгенерирует обработчик этого события, внутри него поместите вызов функций ResizeGlScene() и DrawGlScene(), порядок следования тоже имеет значение. Потому что вначале должно произойти изменений размеров сцены, а потом уже отрисовка.
Уроки OpenGL различных тематик: Выбор обработчика для события Resize Рисунок 3. Выбор обработчика для события Resize.

Листинг 8:

Код:

/*http://esate.ru, KinsT*/

// Обработчик события изменения размеров формы;
        private void FormFS_Resize(object sender, EventArgs e)
        {
            // Вначале изменим размеры сцены;
            ResizeGlScene();
            // А потом перерисуем;
            DrawGlScene();
        }

Теперь оконное масштабируемое приложение готово к работе, смело запускайте! Ну что, ни каких ошибок не обнаружено? Тогда будем двигаться дальше и перейдем непосредственно к инициализации полноэкранного режима.

«Простая инициализация» полноэкранного режима

Добавьте следующий код рисования диска в функцию DrawGlScene(), между Gl.glPushMatrix() и Gl.glPopMatrix(). Этот код нужен только для нас, чтобы мы могли видеть правильность отображения на экране (масштабируемость изображения, отсутствие эффекта «яйца» и т.д.):

Листинг 9:

Код:

/*http://esate.ru, KinsT*/

//
            Gl.glPushMatrix();
            // Здесь можно рисовать что угодно :)
            Glu.GLUquadric disk = Glu.gluNewQuadric();
            Glu.gluQuadricDrawStyle(disk, Glu.GLU_FILL);
            Gl.glColor3ub(255, 0, 150);
            Glu.gluDisk(disk, 0.5, 1.0, 30, 1);

            Gl.glPopMatrix();

Наконец, создадим функцию private void ScreenMode(bool fullscreen), которая отвечает за изменение режима отображения окна – либо в ПР, либо в оконном режиме:

Листинг 10:

Код:

/*http://esate.ru, KinsT*/

// Смена режима (Fullscreen/Window)
        private void ScreenMode(bool fullscreen)
        {
            // Присваиваем значение "глобальной" переменной;
            FS = fullscreen;

            if (FS)
            {   // *** ПОЛНОЭКРАННЫЙ РЕЖИМ ***
                // Скрываем рамку окна;
                this.FormBorderStyle = FormBorderStyle.None;
                // Разворачиваем окно;
                this.WindowState = FormWindowState.Maximized;
                // --- Не обязательный пункт --- 
                // Делаем курсор в форме руки;
                // TaoWin.Cursor = Cursors.Hand;
            }
            else
            {   // *** ОКОННЫЙ РЕЖИМ ***
                // Возвращаем состояние окна;
                this.WindowState = FormWindowState.Normal;
                // Показываем масштабируемую рамку окна;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                // --- Не обязательный пункт ---
                // Возвращаем курсор по-умолчанию;
                // TaoWin.Cursor = Cursors.Default;
                // Задаем размеры окна;
                this.Width = 400;   // Ширина;
                this.Height = 300;  // Высота;
            }
            ResizeGlScene();
        }

Если Вы уже успели заметить, то в приведенном выше коде, нет ни каких особенных трудностей или секретов. Используются только стандартные оконные преобразования путем вызова нужных функций.

Сейчас кто-то может сказать: «То, что здесь написано, не имеет ни какого отношения к игровому режиму!», но если посудить логически и посмотреть, скажем, на исходный код П� написанный на С с применением WinApi функций, то Вы увидите, что там ни чего отличного от нашего кода не происходит (кроме задания вручную формата пикселей для всего экрана). Тем более, что Джель не умеет создавать «свой» собственный ПР, как скажем Managet DirectX.

Итак, что же мы делаем:

Шаг 1. Проверяем флаг ПР. Если мы находимся в ПР, то нужно убрать рамку (Border ;) окна. Далее, присваивая свойству WindowState (отвечает за состояние окна: свернуто, развернуто или восстановлено) параметр FormWindowState.Maximized, разворачиваем наше окно на весь экран.

Шаг 2. Если мы оказались в оконном режиме, то присваиваем свойству WindowState параметр FormWindowState.Normal – восстанавливаем наше окно. Через свойство FormBorderStyle зададим окну границу с изменяемыми размерами (FormBorderStyle.Sizable;).

Шаг 3. В самом конце через свойства Width и Height зададим начальный размер окна, когда его размеры изменены, нужно вызвать функцию изменения размеров OpenGL сцены ResizeGlScene().

Теперь осталось заполнить обработчик событий нажатия клавиатуры. Перейдите к конструктору формы и выделите мышью форму FormFS. Далее зайдите в «Свойства» -> «События» (Events; ), кнопка с желтой молнией (рис. 3).

Выберите свойство KeyUp и нажмите двойным кликом на белом поле. Студия генерирует обработчик события. Нам нужно создать три различных реакции:

  1. Выход из приложения: для выхода из приложения будем использовать клавишу ЕSCAPE. Пишем для нее обработчик, дословно: «Если код НАЖАТОЙ кнопки совпадает с кодом клавиши ЕSCAPE, то завершим наше приложение». Точно такое же правило будет использовано для других кнопок, только вместо «завершим наше приложение» будет прописан вызов соответствующих функций.
  2. Переход в полноэкранный режим: переход в П� будем производить по нажатию на кнопку F2. Когда кнопка нажата вызываем функцию ScreenMode(… ) с параметром true. И прячем наш курсор мыши Cursor.Hide().
  3. Переход в оконный режим: возвращаться в оконный режим будем по нажатию клавиши F1. Когда кнопка нажата вызываем функцию ScreenMode(… ) с параметром false. Показываем курсор Cursor.Show().

Листинг 11:

Код:

/*http://esate.ru, KinsT*/

// События нажатий клавиш клавиатуры; 
        private void FormFS_KeyUp(object sender, KeyEventArgs e)
        {
            #region EXIT
            // Нажата клавиша ЕSCAPE;
            if (e.KeyCode == Keys.Escape)
            {
                // Завершим приложение;
                this.Close();
            }
            #endregion

            #region Полноэкранный или оконный режим
            // Нажата клавиша F2;
            if (e.KeyCode == Keys.F2)
            {
                // Изменяем режим на ПОЛНОЭКРАННЫЙ;
                ScreenMode(true);
                // Прячем курсор;
                Cursor.Hide();
            }
            // Нажата клавиша F1;
            if (e.KeyCode == Keys.F1)
            {
                // Изменяем режим на оконный;
                ScreenMode(false);
                // Показываем курсор;
                Cursor.Show();
            }
            #endregion
        }

Вот, пожалуй, и все!

Компилируем, запускаем и жмем по очереди на кнопки F2, F1, пробуем растягивать наше окно и жмем в конце ЕSCAPE.�

На этом первая часть урока закончилась! В следующей части урока «Полноэкранный режим C# + TAO Framework», мы обогатим наше приложение: добавим возможность выбора разрешения экрана, глубины цвета и частоты обновления экрана.

Жду Ваших комментариев!

ИСТОЧНИКИ:

Михаил Фленов:

http://www.flenov.info/favorite.php?artid=292
http://pmg.org.ru/nehe/nehe01.htm3
http://www.opengl.org.ru/books/open_gl/chapter4.15.html

ФАЙЛЫ ПРОЕКТА

Скачать исходный код проекта (VS 2008)

Проверенное и простое решение

Я искал ответ на этот вопрос в SO и некоторых других сайтах, но один дал ответ, был очень сложным для меня, а некоторые другие ответы просто не работают корректно, поэтому после большого тестирования кода я решил эта головоломка.

Примечание. Я использую Windows 8, а моя панель задач не находится в режиме автоматического скрытия.

Я обнаружил, что установка WindowState в Normal перед выполнением любых изменений остановит ошибку с закрытой панелью задач.

Код

Я создал этот класс, который имеет два метода, первый входит в «полноэкранный режим», а второй оставляет «полноэкранный режим». Таким образом, вам просто нужно создать объект этого класса и передать форму, которую вы хотите установить полный экран, в качестве аргумента методу EnterFullScreenMode или методу LeaveFullScreenMode:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Пример использования

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

Я поставил этот же ответ на другой вопрос, который я не уверен, является ли это дубликат или нет. (Ссылка на другой вопрос: Как отобразить форму Windows в полноэкранном режиме на панели задач?)

Понравилась статья? Поделить с друзьями:
  • Windows form как открыть панель элементов
  • Windows form c visual studio 2019 калькулятор
  • Windows form application visual studio 2019
  • Windows forensics cookbook авторы oleg skulkin scar de courcier
  • Windows folder background changer windows 7 скачать на русском