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 + "\r\n");
}
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。

C#基本语法<三>_WindowsFrom的更多相关文章

  1. PHP语法(三):控制结构(For循环/If/Switch/While)

    相关链接: PHP语法(一):基础和变量 PHP语法(二):数据类型.运算符和函数 PHP语法(三):控制结构(For循环/If/Switch/While) 本文我来总结几个PHP常用的控制结构,先来 ...

  2. Python 基础语法(三)

    Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...

  3. Pocket英语语法---三、英语动词的特点是什么

    Pocket英语语法---三.英语动词的特点是什么 一.总结 一句话总结:即表示时间(时态),又表示人数(单复数) 1.第十七讲,不定量表达法? 1.a few为肯定含义几个,few为否定含义没几个, ...

  4. ios -- 教你如何轻松学习Swift语法(三) 完结篇

    前言:swift语法基础篇(二)来了,想学习swift的朋友可以拿去参考哦,有兴趣可以相互探讨,共同学习哦.      一.自动引用计数   1.自动引用计数工作机制      1.1 swift和o ...

  5. 从零开始学 Web 之 ES6(五)ES6基础语法三

    大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...

  6. 一、JavaScript概述 二、JavaScript的语法 三、JavaScript的内置对象

    一.JavaScript的概述###<1>JavaScript的概念 又称ECMAScript,和java没有任何关系 嵌入在HTML元素中的 被浏览器解释运行的 一种脚本语言. ###& ...

  7. Java基础语法(三)---数组

    一.概念         同一种类型数据的集合.简单的来说就是一容器,用来装东西的. 使用数组的好处:可以自动给数组中的元素从0开始编号,方便操作这些元素. 二.一维数组的格式 格式1:元素类型 [ ...

  8. css基础语法三

    []伪类选择器] 1.写法: 伪类选择器,在选择器后面,用:分隔,紧接伪类状态: eg : .a:link 2. 超链接的伪类状态: :link - 未访问状态 :visited - 已访问状态 :h ...

  9. C# 语法三 抽象类和接口

    1.抽象类 2.接口 一 抽象类 跟普通类的区别: a)用abstract标识类.抽象方法 b)抽象方法,只能声明,不能定义 c)抽象类不能实例化 二 接口 接口用interface标识,所有的成员( ...

随机推荐

  1. 吃透Python上下文管理器

    什么是上下文管理器? 我们常见的with open操作文件,就是一个上下文管理器.如: with open(file, 'rb') as f: text = f.read() 那上下文管理器具体的定义 ...

  2. IE浏览器下载文件保存时提示:“你没有权限在此位置中保存文件”解决办法

    E浏览器下载文件保存时提示 解决办法: 1.Win + R,打开运行命令,输入gpedit.msc,如图所示 2.打开计算机本地组策略编辑器:选择计算机配置-windows设置-安全设置-本地策略-安 ...

  3. Linux_crontab参数表示的意思

    *       *      *       *      * (下面的字体对应) 分     时    日    月    周 星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满 ...

  4. 面试连环炮系列(四):说说TCP的三次握手过程

    说说TCP三次握手的过程? 第一次握手:Client将标志位SYN置为1,随机产生一个值seq=J,并将该数据包发送给Server,Client进入SYN_SENT状态,等待Server确认. 第二次 ...

  5. glusterFS空间不够了怎么办

    查看glusterFS情况 oc project infra-storage oc get all #找到其中一个pod,前缀为 po/glusterfs-registry-xxxx oc exec ...

  6. 使用PIL将图片转成字符

    注意:转化成txt后,txt的字体使用“宋体”,不能使用“微软雅黑”,否则图像会变形 import numpy as npfrom PIL import Image if __name__ == '_ ...

  7. Provide Several View Variants for End-Users 为最终用户提供多个视图变体

    In this lesson, you will learn how to provide several customized variants of the same View, and allo ...

  8. Spring 框架下的 JDBC

    Spring JDBC Spring 对JDBC技术规范做了进一步封装,它又叫Spring JDBCTemplate(jdbc模板技术) 纯JDBC:代码清晰的.效率最高.代码是最烦的.    Spr ...

  9. Python3如何安装pip工具?

    前几天安装Python的时候没有装上pip工具,所以只能现在手动安装了. 首先,访问https://bootstrap.pypa.io/get-pip.py这个网址,然后Ctrl+S将get-pip. ...

  10. VueUI -- iView4.0简单使用

    一.iView(View UI) 1.简介 官网:https://www.iviewui.com/ 仓库:https://github.com/view-design/ViewUI iView 与 V ...