C# Winform初体验

设计一个简单的登录窗口,要求输入用户名:小金,密码:123456时候点登录能正确转到另一个窗口。

1、建立窗体应用。

C# Winform初体验

 2、这里创建一个login和一个NewForm的窗体。

C# Winform初体验

 3、在login的窗体拖拉2个label和2个textbox和1个linklabel的控件。一个标签名字为用户名,一个标签为密码,超链接标签名为登录。

标签的赋名:双击大窗体的边框进入代码界面,在这个代码块对各标签赋名。

4、双击linklabel计入超链接标签的代码块,这里用户判断用户名和密码是否正确,是否跳转另一个窗口等等一些事件。

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 WindowsFormsApp1
{
    public partial class login : Form
    {
        public login()
        {
            InitializeComponent();
        }
        private void Login_Load(object sender, EventArgs e)
        {
            label1.Text = "请输入用户名";
            label2.Text = "请输入密码";
            linkLabel1.Text = "登录";
        }
        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //这里点击登录时给出一个是否确认登录的提示,
            //是就跳转到另一个窗口,否就关闭本窗口,取消关闭消息窗口
            DialogResult dr = MessageBox.Show("是否确定需要登录", "提示",
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                //只有输入用户名:小金,密码:123456时候点登录能正确转到另一个窗口。
                if (textBox1.Text == "小金" && textBox2.Text == "123456")
                {
                    MessageBox.Show("恭喜你,成功登录");
                    NewForm newForm = new NewForm();
                    newForm.Show();
                }
                else//输入不正确提示
                {
                    MessageBox.Show("非常遗憾,成功失败");
            //return;//也可以使用return,直接跳过main函数,立即结束本次方法的执行
this.Close(); } } else if (dr == DialogResult.No) { this.Close(); } else { } } } }

5、在建立窗体即产生的Programe.cs的main方法里面,将最后一行代码的run窗体改为login。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new login());//这里改为需要操作的窗体名称
        }
    }
}
C# Winform初体验