博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#基本语法<三>_WindowsFrom
阅读量:5373 次
发布时间:2019-06-15

本文共 17193 字,大约阅读时间需要 57 分钟。

winform

在windows form开发过程中还是有很多坑需要注意,包括一些重要代码记不得,在这个文件中进行汇总更新。

命名规则

  • M结尾表示model
  • A结尾表示消息
  • Object表示 ,底层接口
  • Presenter表示,逻辑类
  • Transaction表示,具体逻辑
  • View表示界面接口
  • Helper:表示静态函数
  • Statements:表示字符串
  • E表示enum
  • ~BTN按钮
  • 私有变量m_
  • 获得Get
  • 建立Build
  • 生成Generate
  • listbox 为 LB

一个项目体验

using System;using System.Windows.Forms;namespace AerationSystem{    static class Program    {        ///         /// 应用程序的主入口点。        ///         [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            GetAllFrom getform = new GetAllFrom();            getform.MakeLoginForm();            getform.login.ShowDialog();            if(getform.login.DialogResult==DialogResult.OK)            {                getform.MakeAllForm();                Application.Run(getform.currentMain);                //Application.Run(new Form1());            }        }    }}
public class XMLHelper{    ///     /// 读取多行同一标签属性    ///     /// 地址    /// 标签    /// 属性    /// 
多行同一标签属性
public static string[] ReadMultipleTagOneAttribute(string filename,string nodeflag, string strflag) { try { XmlDocument xl = new XmlDocument(); xl.Load(filename); XmlNodeList xnl = xl.GetElementsByTagName("appSettings")[0].ChildNodes; List
vs = new List
(); foreach (XmlNode cn in xnl) { if (cn.Name.Equals(nodeflag)) { vs.Add(cn.Attributes.GetNamedItem(strflag).Value); } } return vs.ToArray(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace + ex.Message); } return null; } ///
/// 读取同一标签多个属性,如果有多个同标签则返回null /// ///
地址 ///
标签 ///
多个属性 ///
多个属性值
public static string[] ReadMultipleAttributeOneTag(string filename, string nodeflag, string[] strflag) { try { XmlDocument xl = new XmlDocument(); xl.Load(filename); XmlNodeList xnl = xl.GetElementsByTagName("appSettings")[0].ChildNodes; List
vs = new List
(); int tagcount = 0; foreach (XmlNode cn in xnl) { if (cn.Name.Equals(nodeflag)) { foreach (string s in strflag) { vs.Add(cn.Attributes.GetNamedItem(s).Value); } tagcount++; } } if (tagcount > 1) { throw new Exception("出现多个相同标签"); } return vs.ToArray(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace + ex.Message); } return null; }}
public class SQLDatabaseHelper{    ///     /// 返回多个表    ///     /// 数据库URL    /// 执行语句    /// 
public static DataSet QueryDs(String dbname, String sqlstr) { OleDbConnection Connection = new OleDbConnection(dbname); try { Connection.Open(); OleDbDataAdapter oleDbAdapter = new OleDbDataAdapter(sqlstr, Connection); DataSet ds = new DataSet(); oleDbAdapter.Fill(ds); return ds; } catch (Exception ex) { Console.WriteLine("打开数据库连接异常:" + ex.Message + "\r\n"); } finally { Connection.Close(); } return null; } /// /// 执行语句返会受影响函数 /// /// 数据库URL /// 执行语句 ///
public static int Execute(String dbname, String sqlstr) { OleDbConnection Connection = new OleDbConnection(dbname); try { Connection.Open(); OleDbCommand oleDbCommand = new OleDbCommand(sqlstr, Connection); return oleDbCommand.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Connection.Close(); } return 0; } /// /// 执行多条语句 /// /// 数据库url /// 受影响的行数 ///
public static int ExecuteAll(string dbname, string[] sqlstrs) { int count = 0; foreach (string s in sqlstrs) { count = count + Execute(dbname, s); } return count; } /// /// 返回表 /// /// 数据库URL /// 执行语句 ///
受影响行数
public static DataTable QueryDt(String dbname, String sqlstr) { OleDbConnection Connection = new OleDbConnection(dbname); try { Connection.Open(); OleDbDataAdapter oleDbAdapter = new OleDbDataAdapter(sqlstr, Connection); OleDbCommandBuilder oleDbBuilder = new OleDbCommandBuilder(oleDbAdapter); DataSet ds = new DataSet(); oleDbAdapter.Fill(ds); return ds.Tables[0]; } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Connection.Close(); } return null; }}
private UserM rowtoUserM(DataRow dr){    if (dr == null) return null;    UserM user = new UserM();    if (!DBNull.Value.Equals(dr["name"])) user.name = dr["name"].ToString();    if (!DBNull.Value.Equals(dr["password"])) user.password = dr["password"].ToString();    if (!DBNull.Value.Equals(dr["active"])) user.active = dr["active"].ToString();    if (!DBNull.Value.Equals(dr["caption"])) user.caption = dr["caption"].ToString();    if (!DBNull.Value.Equals(dr["pri"])) user.pri = dr["pri"].ToString();    return user;}
private SQLDataBaseM strToSqlDatabase(string str){    string catalog, server, username, userpassword;    Match mt = Regex.Match(str, @"server=\w+\.\w+\.\w+\.\w+\,?(\w+)?");    if (!mt.Success)    {        return null;    }    server = mt.Value.Substring(7);    mt = Regex.Match(str, @"id=\w+");    if (!mt.Success)    {        return null;    }    username = mt.Value.Substring(3);    mt = Regex.Match(str, @"password=\w+@?\w+");    if (!mt.Success)    {        return null;    }    userpassword = mt.Value.Substring(9);    mt = Regex.Match(str, @"catalog=\w+");    if (!mt.Success)    {        return null;    }    catalog = mt.Value.Substring(8);    return new SQLDataBaseM(server, catalog, username, userpassword);}
public class SQLStatements{    ///     /// 通过pointcode获得point    ///     public static string GetPointByCodeStr = "select * from TB_MeasurePoint where MPointCode='{0}'";    public static string GetUserByNameAndPasswordStr = "SELECT *  FROM TB_User where name='{0}' and password='{1}'";    public static string GetAllFactoryAreaStr = "select distinct BizType from TB_MeasurePoint where active = '启用'";    public static string GetAllpointTypesStr = "select distinct SignalType from TB_MeasurePoint where active = '启用'";    public static string GetAllEquipmentTypesStr = "select distinct scdtype from TB_MeasurePoint where active = '启用'";    ///     /// 获得钱100个point的值    ///     public static string GetTop100PintsByWhereStr = "select top 100 * from TB_MeasurePoint where {0} AND ParmValue > -9999 order by measuredt desc";    ///     /// 通过约束获得measurepoint    ///     public static string GetPintsByWhereStr = "select * from TB_MeasurePoint where {0}  order by measuredt desc";    ///     /// 获得前100个数据    ///     public static string GetPartlyParasWhereStr = "select top 100 * from tb_mp_{0} where {1} AND ParmValue > -9999 order by measuredt desc";    ///     /// 查询数据获得翻页效果,第一个是code,第二个是(页数-1)*100,第三个是约束    ///     public static string GetParasWhereByPageStr = " select top 100 * from tb_mp_{0} where ItemID not in (select top {1} ItemID from tb_mp_{2} where {3} AND ParmValue > -9999 order by measuredt desc )  AND  {4} AND ParmValue > -9999 order by measuredt desc ";    ///     /// 数量,最大值,最小值,平均值    ///     public static string GetCountMaxMinAvgParaStr = "SELECT COUNT(ParmValue), MAX(ParmValue),MIN(ParmValue),AVG(ParmValue) FROM TB_MP_{0} where {1}  AND ParmValue > -9999";    ///     /// 将点位变成对应数据写到历史数据里    ///     public static string GetSpeciPointsByWhereStr = "select MPOINTID,MPOINTCODE,PARMNAME,ISNULL(ParmName, '未知') +'['+MPOINTCODE+']' as 测量点,alarmmax as 超标上限,alarmmin as 超标下限,forcemax as 纵轴上限,forcemin as 纵轴下限,spanrange as 量程,rate,SignalType,Unit,NumTail,biztype,scdtype,morder from TB_MeasurePoint where {0} AND ParmValue > -9999 order by measuredt desc";    ///     /// 获得point的第二个值    ///     public static string GetSecondValueByCodeStr = "select top 2 ParmValue from tb_mp_{0} where  ParmValue > -9999 order by measuredt desc";    ///     /// 获得点的最新的数据时间    ///     public static string GetLastDateTimeByCodeStr = "select top 1 measuredt  from tb_mp_{0} where ParmValue > -9999 order by measuredt desc";    public static string GetPointDataByCodeStr = "select  * from tb_mp_{0} where {1} AND ParmValue > -9999 order by measuredt desc";}
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
public void GenerateReportTable(SearchConstrainA sca){    if (sca != null)    {        string startpath = Application.StartupPath + "\\日报表\\";        if (!Directory.Exists(startpath))        {            Directory.CreateDirectory(startpath);        }        startpath = startpath + "" + sca.reporttime.ToString() + sca.PumpType.ToString()+".xls";        ExcelHelper.CopyExcel(startpath);        DataTable dt = database.GetDataFromSC(sca);        if (dt == null)        {            allFrom.form.ShowMessageBox(sca.reporttime + "没有数据");            return;        }        allFrom.form.ShowMessageBox("写入参数", ExcelHelper.FillExcel(dt, startpath, sca));    }}
using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace PunchReport{    public class ExcelHelper    {        public static void CopyExcel(string targetpath)        {            Excel.Application xApp = new Excel.ApplicationClass();            xApp.WindowState = Excel.XlWindowState.xlMinimized;            xApp.DisplayAlerts = false;            xApp.Visible = false;            object MissingValue = Type.Missing;            Excel.Workbook xBook = xApp.Workbooks._Open(@"" + Application.StartupPath + "\\report.xls",                    MissingValue, MissingValue, MissingValue, MissingValue                    , MissingValue, MissingValue, MissingValue, MissingValue                    , MissingValue, MissingValue, MissingValue, MissingValue);            xBook._SaveAs(@"" + targetpath, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, Excel.XlSaveAsAccessMode.xlNoChange, MissingValue, MissingValue, MissingValue, MissingValue);            xBook = null;            xApp.Quit();            Kill(xApp);            xApp = null;        }        public static bool FillExcel(DataTable dt, string targetpath,SearchConstrainA sca)        {            if (dt == null && dt.Rows.Count < 0) return false;            object MissingValue = Type.Missing;            Excel.Application xApp = new Excel.ApplicationClass();            Excel.Workbook xBook;            xApp.WindowState = Excel.XlWindowState.xlMinimized;            xApp.DisplayAlerts = false;            xApp.Visible = false;            try            {                xBook = xApp.Workbooks._Open(@"" + targetpath,                       MissingValue, MissingValue, MissingValue, MissingValue                       , MissingValue, MissingValue, MissingValue, MissingValue                       , MissingValue, MissingValue, MissingValue, MissingValue);                Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets["统计表"];                Excel.Range tilterng = xSheet.get_Range("A1", MissingValue);                tilterng.Value2 = sca.PumpType.ToString() + "日报表";                Excel.Range tmprng = xSheet.get_Range("A2", MissingValue);                tmprng.Value2 = "报表日期:  " + DateTime.Parse(sca.reporttime).ToString("yyyy年MM月dd日");                for (int j = 0; j < dt.Rows.Count; j++)                {                    for (int i = 0; i < 4; i++)                    {                        tmprng = xSheet.get_Range(getColName("A", i) + (4 + j).ToString(), MissingValue);                        bool a = true;                        if (tmprng.HasFormula.Equals(a))                        {                            continue;                        }                        else                        {                            tmprng.Value2 = dt.Rows[j][i].ToString();                        }                    }                }                xBook.Save();                return true;            }            catch (Exception ex)            {                BackLogHelper.LogWrite(ex.StackTrace + ex.Message);                return false;            }            finally            {                xBook = null;                xApp.Quit();                Kill(xApp);                xApp = null;            }                    }        private static string getColName(string strTemp, int inc)        {            int i = strTemp.Length;            char[] ca = new char[i];            ca = strTemp.ToCharArray();            int w = i - 1;            int AddResult = (int)ca[w];            AddResult += inc;            if (AddResult >= 91)//需要进一            {                ca[w] = (char)(AddResult - 91 + 65);                if (w > 0)                {                    ca[w - 1] = (char)((int)ca[w - 1] + 1);                    strTemp = ca[w - 1].ToString() + ca[w].ToString();                }                else                {                    strTemp = "A" + ca[w].ToString();                }            }            else            {                strTemp = "";                ca[w] = (char)(AddResult);                while (w >= 0)                {                    strTemp = ca[w].ToString() + strTemp;                    w--;                }            }            return strTemp;        }        [DllImport("User32.dll", CharSet = CharSet.Auto)]        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);        public static void Kill(Excel.Application xlapp)        {            try            {                IntPtr app = new IntPtr(xlapp.Hwnd);  //得到这个句柄,具体作用是得到这块内存入口                 int processid = 0;                GetWindowThreadProcessId(app, out processid);  //得到本进程唯一标志k                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(processid);                p.Kill();    //关闭进程k            }            catch            { }        }    }}
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace PunchReport{    public class BackLogHelper    {        public static void LogWrite(String memo)        {            try            {                StreamWriter sr;                //String filename = DateTime.Now.ToShortDateString() + ".txt";                String filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";                if (!Directory.Exists(Application.StartupPath + "\\logs\\log\\"))                {                    Directory.CreateDirectory(Application.StartupPath + "\\logs\\log\\");                }                if (!File.Exists(Application.StartupPath + "\\logs\\log\\" + filename))                {                    sr = File.CreateText(Application.StartupPath + "\\logs\\log\\" + filename);                    sr.Close();                }                sr = File.AppendText(Application.StartupPath + "\\logs\\log\\" + filename);                sr.WriteLine(memo);                sr.Close();            }            catch (System.Exception ex)            {                Console.WriteLine("写入日志异常:" + ex);            }        }    }}
string sqlname = ConfigurationManager.AppSettings["SQLName"].ToString();string sqlip = ConfigurationManager.AppSettings["SQLIP"].ToString();string userid = ConfigurationManager.AppSettings["UserID"].ToString();string userpassword = ConfigurationManager.AppSettings["UserPassword"].ToString();string removesstr= ConfigurationManager.AppSettings["Remove"].ToString();

自定义控件

  • Screen.PrimaryScreen.WorkingArea.Width;获取桌面宽度,hight高度
  • this.size程序宽度
  • base.Invalidate(this.MenuRect)重绘矩形区域
  • this.FormBorderStyle = FormBorderStyle.None;无边框
  • this.SetStyle(
    ControlStyles.AllPaintingInWmPaint |
    ControlStyles.OptimizedDoubleBuffer |
    ControlStyles.ResizeRedraw |
    ControlStyles.Selectable |
    ControlStyles.ContainerControl |
    ControlStyles.UserPaint, true);
    this.SetStyle(ControlStyles.Opaque, false);
    this.UpdateStyles();
    绘制控件样式
  • Graphics g = e.Graphics;获取画布,如果是创建的使用完后要注销
  • FormWindowState.Maximized窗口状态
  • FormStartPosition.CenterParent窗体开启位置
  • 继承form的重载类中WndProc有窗体循环,在该循环中提前捕获消息进行拦截。
  • 设置背景图片 totalpic.ImageLocation = System.Windows.Forms.Application.StartupPath + "\img\" + comboBox2.Text.ToString() + ".jpg";

  • 使得panel1不可见的时候panel2填满panel1的区域,让panel1的dock设置为top,panel2的dock设置为fill。

转载于:https://www.cnblogs.com/lovexinyi/p/10071567.html

你可能感兴趣的文章
MES架构
查看>>
hdu 2767(tarjan)
查看>>
sklearn之分类模型混淆矩阵和分类报告
查看>>
MySQL各存储引擎
查看>>
项目--简单导出CSV文件
查看>>
Oracle session相关数据字典(一)
查看>>
BZOJ 3399 [Usaco2009 Mar]Sand Castle城堡(贪心)
查看>>
获取元素属性get_attribute
查看>>
在Flex中用Validator检测数字、字符串、Email.
查看>>
[leetcode]4Sum
查看>>
POJ1062 昂贵的聘礼
查看>>
【零基础学习iOS开发】【02-C语言】08-基本运算
查看>>
Java 将指定字符串连接到此字符串的结尾 concat()
查看>>
Hibernate Criterion
查看>>
Python知识
查看>>
我们为什么要搞长沙.NET技术社区(三)
查看>>
杭电acm Cake
查看>>
js函数中this的指向
查看>>
c++ 引用方式传递数组
查看>>
HBase学习之路 (九)HBase phoenix的使用
查看>>