How do I make a WinForms app go Full Screen

前端 未结 9 1507
你的背包
你的背包 2020-11-22 11:20

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 <

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 11:51

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

提交回复
热议问题