Winform登陆+验证码+链接数据库+窗口切换

来源:互联网 发布:男生不喜欢女生 知乎 编辑:程序博客网 时间:2024/06/11 13:15

登陆窗口:Form_login.cs

数据库链接类 :SQLhelper.cs (用的sqlserver)
用户类:LoginUser.CS
验证码:UpdateCode.cs

登陆窗口 Form_login.cs
using MedicalRecord.Class;using System;using System.Windows.Forms;namespace MedicalRecord{    public partial class Form_login : DevComponents.DotNetBar.OfficeForm    {        //数据库链接类 和用户类        private SQLhelper sqLhelper = new SQLhelper();        private static LoginUser LoginUser = new LoginUser();        private string code = String.Empty;        public Form_login()        {            InitializeComponent();        }        //登陆按钮        private void Login_Click(object sender, EventArgs e)        {            // 判断输入的是否为空 ,如果为空需要提醒            //判断是否输入了账号            if (string.IsNullOrEmpty(this.Skin_usercode.Text))            {                MessageBox.Show("用户名必须输入!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                Skin_usercode.Focus();                return;            }            //判断是否输入密码            if (string.IsNullOrEmpty(Skin_password.Text))            {                MessageBox.Show("密码必须输入!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                Skin_password.Focus();                return;            }            //如果没有的话把输入的赋值给loginuser 类            LoginUser.Usercode = Skin_usercode.Text;            LoginUser.Password = Skin_password.Text;            //去访问数据库,查询是否存在该用户            string selectSql =                string.Format("select  count(*) from mris.dbo.sys_user where usercode = '{0}'   and password = '{1}' ",                    LoginUser.Usercode, LoginUser.Password);            //接受数据库返回信息            //ExecuteScalar 执行一条返回第一条记录第一列的SqlCommand命令            int ss = (int) sqLhelper.ExecuteScalar(selectSql);            //如果存在就将 DialogResult.OK,否则提示不存在            if (ss == 1)            {                this.DialogResult = DialogResult.OK;            }            else            {                MessageBox.Show("用户密码不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                Skin_password.Clear();                Skin_usercode.Clear();                Skin_usercode.Focus();                return;            }        }        //窗口打开的时候就生成一个验证码        private void Form_login_Load(object sender, EventArgs e)        {            change();        }        private void cde_Click(object sender, EventArgs e)        {            change();        }        private void cde_DoubleClick(object sender, EventArgs e)        {            change();        }        public void change()        {            UpdateCode updateCode = new UpdateCode();            code = updateCode.MakeRandomCode(4);            this.cde.Image = updateCode.MakeImage(code, this.cde.Width, this.cde.Height);        }    }}
用户类:LoginUser.CS
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MedicalRecord.Class{    public  class LoginUser    {        private string _usercode;        public string Usercode        {            get { return _usercode; }            set { _usercode = value; }        }        private string _password;        public string Password        {            get { return _password; }            set { _password = value; }        }    }}

验证码:UpdateCode.cs
using System;using System.Collections;using System.Collections.Generic;using System.Drawing;using System.Drawing.Drawing2D;namespace MedicalRecord.Class{    public class UpdateCode    {        public string  MakeRandomCode(int codelenght)        {            return CreateRandomCode(codelenght);        }        public Bitmap MakeImage(string codestring ,int width ,int height)        {            return CreateImage(codestring, width, height);        }        private string CreateRandomCode(int codelenght)        {            int rand;            char code;            String RandomCode = String.Empty;            Random random = new Random();            for (int i = 0; i < codelenght; i++)            {                rand = random.Next();                if (rand%3 == 0)                {                    code = (char) ('A' + (char) (rand%26));                }                if (rand%3 == 1)                {                    code = (char) ('a' + (char) (rand%26));                }                else                {                    code = (char) ('0' + (char) (rand%10));                }                RandomCode += code;            }            return RandomCode;        }        private Bitmap CreateImage(string RandCode ,int width ,int height )        {            Bitmap map = new Bitmap(width, height);            Graphics graph = Graphics.FromImage(map);            graph.Clear(Color.AliceBlue);            graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, width - 1, height - 1); //画一个边框            graph.SmoothingMode = SmoothingMode.AntiAlias; //            Random rand = new Random();            //背景噪点生成            Pen blackpen = new Pen(Color.Gray, 0);            for (int i = 0; i < 50; i++)            {                int y = rand.Next(0, height);                int x = rand.Next(0, width);                graph.DrawRectangle(blackpen, x, y, 1, 1);            }            //文字距中            char[] chars = RandCode.ToCharArray();            StringFormat format = new StringFormat(StringFormatFlags.NoClip);            format.Alignment = StringAlignment.Center;            format.LineAlignment = StringAlignment.Center;            //定义字体            Color[] c =            {                Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan,                Color.Purple            };            string[] font = {"Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体"};            for (int i = 0; i < chars.Length; i++)            {                int cindex = rand.Next(7);                int findex = rand.Next(5);                Font f = new Font(font[findex], 13, FontStyle.Bold); //字体样式(参数2为字体大小)                Brush b = new SolidBrush(c[cindex]);                Point dot = new Point(16, 16);                float angle = rand.Next(-45, 45); //转动的度数                graph.TranslateTransform(dot.X, dot.Y); //移动光标到指定位置                graph.RotateTransform(angle);                graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);                graph.RotateTransform(-angle); //转回去                graph.TranslateTransform(2, -dot.Y); //移动光标到指定位置            }            return map  ;        }    }}

数据库链接类 :SQLhelper.cs
using System.Data;using System.Data.SqlClient;namespace MedicalRecord.Class{    internal class SQLhelper    {        private static readonly string DateSource = "(Local)";        private static readonly string Initial = "";//写库名        private static readonly string User = "sa";        private static readonly string Password = " ";//写密码        private static readonly string connectionString =            string.Format(                "Data Source={0};Pooling=False;Max Pool Size = 1024;Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",                DateSource, Initial, User, Password);        public static SqlConnection conn;        //打开数据库连接        public static void OpenConn()        {            conn = new SqlConnection(connectionString);            if (conn.State.ToString().ToLower() != "open")            {                conn.Open();            }        }        //关闭数据库连接        public static void CloneConn()        {            if (conn.State.ToString().ToLower() != "open")            {                conn.Close();                conn.Dispose();            }        }        // 读取数据        public static SqlDataReader GetDataReaderValue(string sql)        {            OpenConn();            SqlCommand command = new SqlCommand(sql, conn);            SqlDataReader dataReader = command.ExecuteReader();            CloneConn();            return dataReader;        }        // 返回DataSet        public DataSet GetDataSetValue(string sql, string tablename)        {            OpenConn();            DataSet dataSet = new DataSet();            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, conn);            sqlDataAdapter.Fill(dataSet, tablename);            CloneConn();            return dataSet;        }        //  返回DataView        public DataView GetDataViewVaule(string sql)        {            OpenConn();            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, conn);            DataSet dataSet = new DataSet();            sqlDataAdapter.Fill(dataSet, "temp");            CloneConn();            return dataSet.Tables[0].DefaultView;        }        //  返回DataView        public DataTable GetDataTableValue(string sql)        {            OpenConn();            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();            DataTable dataTable = new DataTable();            sqlDataAdapter.Fill(dataTable);            CloneConn();            return dataTable;        }        // 执行一个SQL操作:添加、删除、更新操作        public void ExecuteNonQuery(string sql)        {            OpenConn();            SqlCommand command = new SqlCommand(sql, conn);            command.ExecuteNonQuery();            command.Dispose();            CloneConn();        }        // 执行一个SQL操作:添加、删除、更新操作,返回受影响的行        public int ExecuteNonQueryCount(string sql)        {            OpenConn();            SqlCommand cmd = new SqlCommand(sql, conn);            int value = cmd.ExecuteNonQuery();            return value;        }        //执行一条返回第一条记录第一列的SqlCommand命令        public object ExecuteScalar(string sql)        {            OpenConn();            SqlCommand cmd = new SqlCommand(sql, conn);            object value = cmd.ExecuteScalar();            return value;        }        // 返回记录数        public int SqlServerRecordCount(string sql)        {            OpenConn();            SqlCommand cmd = new SqlCommand(sql, conn);            SqlDataReader dr = cmd.ExecuteReader();            int RecordCount = 0;            while (dr.Read())            {                RecordCount = RecordCount + 1;            }            CloneConn();            return RecordCount;        }    }}   
Program 里:
 internal static class Program    {        /// <summary>        /// The main entry point for the application.        /// </summary>        [STAThread]        private static void Main()        {            bool ret;            Mutex mutex = new Mutex(true, Application.ProductName, out ret);            if (ret)            {                try                {                    Application.EnableVisualStyles();                    Application.SetCompatibleTextRenderingDefault(false);                    Form_login fl = new Form_login();                    if (fl.ShowDialog() == DialogResult.OK)                    {                        Application.Run(new Main());                    }                    mutex.ReleaseMutex();                }                catch (Exception ex)                {                    MessageBox.Show(null, ex.ToString(), Application.ProductName,                                       MessageBoxButtons.OK, MessageBoxIcon.Warning);                    Application.Exit();                }            }            Application.EnableVisualStyles();        }    }