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

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

264k31 gold badges332 silver badges515 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,89612 gold badges40 silver badges62 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.4k8 gold badges51 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

3101 gold badge5 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.4k8 gold badges51 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,39710 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

4865 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

Need to display a window in «real full screen» mode, including when there are several monitors? It’s very simple and all in one line:

this.DesktopBounds = SystemInformation.VirtualScreen;

To be placed in the constructor of the window for example.

Be careful if you set this.TopMost = True because the window will cover the taskbar which will therefore be inaccessible.

answered Jun 21 at 8:42

damien's user avatar

0 / 0 / 0

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

Сообщений: 46

1

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

14.04.2012, 09:11. Показов 91574. Ответов 7


Студворк — интернет-сервис помощи студентам

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



0



DimanRu

719 / 710 / 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



Rynosce

21 / 21 / 2

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

Сообщений: 39

07.06.2023, 14:03

8

   На заголовке формы по умолчанию есть 3 кнопки
   1) Свернуть
   2) Развернуть , Свернуть в окно
   3) Закрыть
   

   Вот какой код использует форма для этих кнопок

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Свернуть
WindowState = FormWindowState.Minimized;
 
// Развернуть , Свернуть в окно:
if (WindowState == FormWindowState.Maximized)
{
    WindowState = FormWindowState.Normal;
}
else if (WindowState == FormWindowState.Normal)
{
    WindowState = FormWindowState.Maximized;
}
 
// Закрыть всплывающее или диалоговое окно
this.Close();
 
// Если нужно закрыть всё приложение со всеми окнами
Application.Exit();

Изображения

 



0



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


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

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

Для Windows Forms:

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

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

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


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

09 окт. 2023, в 11:22

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

09 окт. 2023, в 11:14

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

09 окт. 2023, в 11:12

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

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

Windows Forms — это один из основных инструментов для разработки пользовательских интерфейсов в Windows приложениях. Одним из распространенных вопросов разработчиков является возможность открыть окно Windows Forms на полный экран. В этой статье мы расскажем о том, как это сделать.

Первым шагом для открытия окна Windows Forms на весь экран является использование свойства WindowState. Установите его значение равным FormWindowState.Maximized. Это позволит окну открыться в максимально возможном размере, занимая весь экран.

Однако, такое открытие окна может быть неправильным, если задача состоит в том, чтобы открыть окно в полноэкранном режиме, без панели задач и заголовка окна. Для этого необходимо использовать Win API функции ShowWindow и SetWindowLong.

Для более подробной информации о том, как открыть Windows Forms на весь экран, следуйте нашей подробной инструкции с примерами кода.

Содержание

  1. Как максимально увеличить размер окна windows forms
  2. Подготовка к изменению размера окна
  3. Установка максимального размера окна

Как максимально увеличить размер окна windows forms

Бывают ситуации, когда требуется максимально увеличить размер окна windows forms для того, чтобы обеспечить наибольшую комфортность пользователю. В этой статье мы рассмотрим подробную инструкцию о том, как это сделать.

Для максимального увеличения размера окна можно использовать свойство WindowState. Оно позволяет установить состояние окна, включая размеры и положение на экране.

Вот пример кода, показывающий, как использовать свойство WindowState для увеличения размера окна:


// Установка состояния окна на максимизированное
this.WindowState = FormWindowState.Maximized;

В данном примере кода свойство WindowState устанавливается в значение FormWindowState.Maximized, что приводит к максимизации окна на весь экран.

Если вы хотите установить только ширину или высоту окна, можно использовать свойства Width и Height соответственно:


// Увеличение ширины окна
this.Width = 1200;
// Увеличение высоты окна
this.Height = 800;

В данном примере кода свойства Width и Height устанавливаются в требуемые значения, что приводит к увеличению соответствующих размеров окна.

Если вам нужно увеличить размеры окна относительно текущих размеров, можно использовать свойство Size:


// Увеличение размеров окна относительно текущих размеров
this.Size = new Size(this.Width * 2, this.Height * 2);

В данном примере кода свойство Size устанавливается в новый объект Size, созданный на основе текущих значений ширины и высоты окна, умноженных на 2.

Теперь вы знаете, как максимально увеличить размер окна windows forms, используя свойства WindowState, Width, Height и Size. Это позволит вам создавать более удобные и масштабируемые пользовательские интерфейсы.

Подготовка к изменению размера окна

Перед тем, как открыть окно Windows Forms на весь экран, вам понадобится выполнить несколько подготовительных шагов:

  1. Откройте проект Windows Forms в вашей среде разработки (например, в Visual Studio).
  2. Внесите необходимые изменения в дизайн вашей формы. Например, вы можете добавить элементы управления или изменить расположение существующих элементов для лучшего использования доступного места на экране.
  3. Убедитесь, что все элементы вашей формы имеют свойство Anchor или Dock заданное таким образом, чтобы они могли масштабироваться правильно при изменении размера окна. Например, вы можете задать свойство Anchor равным Top,left,right,bottom для элементов, которые должны выровняться с краями окна.
  4. Перейдите к коду вашей формы и найдите метод Form_Load. Если этот метод отсутствует, создайте его.
  5. Внутри метода Form_Load добавьте следующий код:

private void Form_Load(object sender, EventArgs e)
{
// Развернуть окно на весь экран
WindowState = FormWindowState.Maximized;
}

Этот код будет выполняться при загрузке формы и автоматически развернет окно на весь экран. Теперь вы готовы открыть окно Windows Forms на весь экран и наслаждаться полным использованием доступного пространства.

Установка максимального размера окна

Чтобы установить максимальный размер окна в Windows Forms, можно использовать свойство MaximumSize объекта Form. Это свойство позволяет задать максимальную ширину и высоту окна.

Приведенный ниже пример демонстрирует, как установить максимальный размер окна с использованием свойства MaximumSize:

Свойство Значение
FormBorderStyle Sizable
MaximumSize {Width = 800, Height = 600}

В данном примере окно будет иметь стиль Sizable, то есть пользователь сможет изменять его размер. Максимальный размер окна будет ограничен значениями 800 пикселей по ширине и 600 пикселей по высоте.

Чтобы установить эти значения для свойств, можно воспользоваться конструктором класса Size:


form.FormBorderStyle = FormBorderStyle.Sizable;
form.MaximumSize = new Size(800, 600);

После выполнения этих строк кода окно будет иметь установленный максимальный размер.

  • Download demo project — 13.65 KB

Sample Image - MaxWinForm.png

Introduction

One of the sounds-like-simple questions is “how to make your application truly Full Screen”, i.e. not showing Taskbar or anything like that.

The initial approach is obvious…

targetForm.WindowState = FormWindowState.Maximized;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.TopMost = true;

… assuming that the target form is referenced with targetForm.

Does it work? Well, sort of. If your Taskbar has default setting unchecked for “Keep the taskbar on top of other Windows”, this will present your application in all its glory all over the screen estate.

However, if the Taskbar is set to appear on top of all others, this won’t help — your application won’t cover it.

Update For This Approach

In the discussion of the article (below) Azlan David (thanks David!) suggested to try this approach:

targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;

(Just changed the order of property assignments.) It does the work on all Win XP SP2 computers where I had the opportunity to test it; however, on one Win 2003 SP1 computer, this did not help; I’m still investigating why.

Let’s go further — the next step is to use P/Invoke and to engage the Win32 API services. There is an easy way to hide a particular window. So, find the Taskbar and hide it:

private const int SW_HIDE = 0;
private const int SW_SHOW = 1;

[DllImport("user32.dll")]
private static extern int FindWindow(string className, string windowText);
[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int command);

int hWnd = FindWindow("Shell_TrayWnd", "");
ShowWindow(hWnd, SW_HIDE);

targetForm.WindowState = FormWindowState.Maximized;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.TopMost = true;

(You need to add using System.Runtime.InteropServices;)

Is this better? In theory, yes — the Taskbar is hidden, but your application still does not occupy the whole screen — the place where the Taskbar was is not used.

The real and proven solution is to make a request to WinAPI that your form take the whole screen estate — Taskbar will hide itself in that case. Full information about that can be found in the KB article Q179363: How To Cover the Task Bar with a Window.

The steps are as follows:

  • Find out the dimension of the screen estate by calling GetSystemMetrics
  • Set the dimensions of your form to full screen

Here is the actual code:

public class WinApi
{
    [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
    public static extern int GetSystemMetrics(int which);

    [DllImport("user32.dll")]
    public static extern void
        SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
                     int X, int Y, int width, int height, uint flags);        

    private const int SM_CXSCREEN = 0;
    private const int SM_CYSCREEN = 1;
    private static IntPtr HWND_TOP = IntPtr.Zero;
    private const int SWP_SHOWWINDOW = 64; 

    public static int ScreenX
    {
        get { return GetSystemMetrics(SM_CXSCREEN);}
    }

    public static int ScreenY
    {
        get { return GetSystemMetrics(SM_CYSCREEN);}
    }

    public static void SetWinFullScreen(IntPtr hwnd)
    {
        SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
    }
}

public class FormState
{
    private FormWindowState winState;
    private FormBorderStyle brdStyle;
    private bool topMost;
    private Rectangle bounds;

    private bool IsMaximized = false;

    public void Maximize(Form targetForm)
    {
        if (!IsMaximized)
        {
            IsMaximized = true;
            Save(targetForm);
            targetForm.WindowState = FormWindowState.Maximized;
            targetForm.FormBorderStyle = FormBorderStyle.None;
            targetForm.TopMost = true;
            WinApi.SetWinFullScreen(targetForm.Handle);
        }
    }

    public void Save(Form targetForm)
    {
        winState = targetForm.WindowState;
        brdStyle = targetForm.FormBorderStyle;
        topMost = targetForm.TopMost;
        bounds = targetForm.Bounds;
    }

    public void Restore(Form targetForm)
    {
        targetForm.WindowState = winState;
        targetForm.FormBorderStyle = brdStyle;
        targetForm.TopMost = topMost;
        targetForm.Bounds = bounds;
        IsMaximized = false;
    }
}

Now you can use the above class in your WinForms application like this:

public partial class MaxForm : Form
{
    FormState formState = new FormState();

    public MaxForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        formState.Maximize(this);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        formState.Restore(this);
    }
}

The full code and example application can be downloaded from the link at the top of this article.

History

  • 3rd December, 2006: Initial post

  • Windows forms нарисовать круг c
  • Windows form c background image
  • Windows forms как создать файл
  • Windows form ссылка на объект не указывает на экземпляр объекта
  • Windows forms как запретить изменять размер окна