按钮操作窗体

环境介绍:

  • 代码工具: Visual Studio 2022
  • 开发框架: .net formwork 4.7.2

开发须知

当前我所了解的有.net core以及.net formwork两种框架
.net formwork:
这个是微软专用的框架,简单来说你所生成的可执行程序在其他电脑上是可以直接运行的,不需要安装环境,因为默认就已经有了。限制就是只能在windows上运行,根据选择的框架不同受限不同的windwos操作系统。默认高版本的.net formwork兼容低版本的.net formwork。

.net core:
这个框架适用于跨平台(windwos\linux\macos),但是前提是需要安装.net core的环境。简单来,如果你开发的可执行程序需要在其他电脑上运行,那么就必须在需要运行的电脑上安装.net core环境,要不然执行不了 -. -

创建项目

打开Visual Studio 准备创建项目
image

创建一个net formwork项目
image

image

布局一个按钮

image

创建一个新的窗体

创建的一个新的窗体用于第一个窗体中的按钮进行跳转

image

image

image

编写窗体1中的按钮代码

image

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace button
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.ShowDialog();
        }
    }
}

窗体2新增按钮

image

编写关闭窗口代码

新建一个类文件,用于保存窗口1加载的时候的对象
image

image

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace button
{
    public static class TestClass
    {
        public static Form1 frm1;
    }
}

窗体1中加载窗体时代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace button
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 加载窗体的时候将窗体对象赋予给frm1
            TestClass.frm1 = this;
        }
    }
}

窗体2中按钮逻辑

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace button
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //关闭窗体1,所有窗体全部关闭
            TestClass.frm1.Close();
        }
    }
}

posted @ 2022-09-22 16:07  枸杞泡茶呀  阅读(55)  评论(0)    收藏  举报