Maximize, minimize, restore, close and move the form of winform in C#

Maximize, minimize, restore, close and move the form of winform in C#

When beautifying the winform form interface, generally modify the FormBorderStyle property of the form to None, and then the form will become a blank "white paper", and then design the interface according to your needs. The close, minimize, and maximize buttons on the form all need to be added by themselves. The code to achieve their functions is as follows:

        //窗体的关闭
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //窗体最小化
        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        //窗体最大化以及还原
        private void btnMax_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                Image backImage = Resources.最大化;//这里图片调用的时资源库中添加好的图片  需要添加引用 using CalibrationAndMatching.Properties;
                btn_Max.BackgroundImage = backImage;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
                Image backImage = Resources.还原;
                btn_Max.BackgroundImage = backImage;
            }
        }

After clicking the window maximize button, you will find that the window becomes larger and covers the entire screen, covering the taskbar. The solution to this problem is as follows:

        //在窗体的Load事件中编写
        private void Form1_Load(object sender, EventArgs e)
        {
            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
        }

To realize the dragging of the form, put the following code into the MouseDown event of the control:

        //调用API函数  添加引用using System.Runtime.InteropServices;
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        private void FrmMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1)
            {
                //窗体移动
                if (e.Button == MouseButtons.Left)
                {
                    ReleaseCapture(); //释放鼠标捕捉
                    //发送左键点击的消息至该窗体(标题栏)
                    SendMessage(this.Handle, 0xA1, 0x02, 0);
                }
            }
        }

 

Guess you like

Origin blog.csdn.net/Kevin_Sun777/article/details/108953773