C#基本语法<三>_WindowsFrom

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
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [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
{
    /// <summary>
    /// 读取多行同一标签属性
    /// </summary>
    /// <param name="filename">地址</param>
    /// <param name="nodeflag">标签</param>
    /// <param name="strflag">属性</param>
    /// <returns>多行同一标签属性</returns>
    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<string> vs = new List<string>();
            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;
    }
    /// <summary>
    /// 读取同一标签多个属性,如果有多个同标签则返回null
    /// </summary>
    /// <param name="filename">地址</param>
    /// <param name="nodeflag">标签</param>
    /// <param name="strflag">多个属性</param>
    /// <returns>多个属性值</returns>
    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<string> vs = new List<string>();
            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
{
    /// <summary>
    /// 返回多个表
    /// </summary>
    /// <param name="dbname">数据库URL</param>
    /// <param name="sqlstr">执行语句</param>
    /// <returns></returns>
    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 + "
");
        }
        finally
        {

            Connection.Close();
        }
        return null;
    }
    /// <summary>
    /// 执行语句返会受影响函数
    /// </summary>
    /// <param name="dbname">数据库URL</param>
    /// <param name="sqlstr">执行语句</param>
    /// <returns></returns>
    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;
    }
    /// <summary>
    /// 执行多条语句
    /// </summary>
    /// <param name="dbname">数据库url</param>
    /// <param name="sqlstrs">受影响的行数</param>
    /// <returns></returns>
    public static int ExecuteAll(string dbname, string[] sqlstrs)
    {
        int count = 0;
        foreach (string s in sqlstrs)
        {
            count = count + Execute(dbname, s);
        }
        return count;
    }
    /// <summary>
    /// 返回表
    /// </summary>
    /// <param name="dbname">数据库URL</param>
    /// <param name="sqlstr">执行语句</param>
    /// <returns>受影响行数</returns>
    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
{
    /// <summary>
    /// 通过pointcode获得point
    /// </summary>
    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 = '启用'";
    /// <summary>
    /// 获得钱100个point的值
    /// </summary>
    public static string GetTop100PintsByWhereStr = "select top 100 * from TB_MeasurePoint where {0} AND ParmValue > -9999 order by measuredt desc";
    /// <summary>
    /// 通过约束获得measurepoint
    /// </summary>
    public static string GetPintsByWhereStr = "select * from TB_MeasurePoint where {0}  order by measuredt desc";

    /// <summary>
    /// 获得前100个数据
    /// </summary>
    public static string GetPartlyParasWhereStr = "select top 100 * from tb_mp_{0} where {1} AND ParmValue > -9999 order by measuredt desc";
    /// <summary>
    /// 查询数据获得翻页效果,第一个是code,第二个是(页数-1)*100,第三个是约束
    /// </summary>
    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 ";
    /// <summary>
    /// 数量,最大值,最小值,平均值
    /// </summary>
    public static string GetCountMaxMinAvgParaStr = "SELECT COUNT(ParmValue), MAX(ParmValue),MIN(ParmValue),AVG(ParmValue) FROM TB_MP_{0} where {1}  AND ParmValue > -9999";

    /// <summary>
    /// 将点位变成对应数据写到历史数据里
    /// </summary>
    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";
    /// <summary>
    /// 获得point的第二个值
    /// </summary>
    public static string GetSecondValueByCodeStr = "select top 2 ParmValue from tb_mp_{0} where  ParmValue > -9999 order by measuredt desc";
    /// <summary>
    /// 获得点的最新的数据时间
    /// </summary>
    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);
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <appSettings>
    <add key = "SQLName" value="EIP_PRD_JSXJ"/>
    <add key = "SQLIP" value="127.0.0.1"/>
    <add key = "UserID" value="sa"/>
    <add key="SearchTable" value="KQview"/>
    <add key="Remove" value="巡检A组,巡检B组"/>
  </appSettings>
</configuration>

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