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. uni-app开发小程序入门到崩溃

    最近一段时间公司要做一个小程序项目,还要支持,微信小程序,头条小程序,百度小程序.一套代码,实现三个平台.当时接到这个任务,就不知道怎么去下手,一套代码,分别要发布三个平台,赶紧就去上网了解这些东西, ...

  2. Android Activity启动流程, app启动流程,APK打包流程, APK安装过程

    1.Activity启动流程 (7.0版本之前) 从startActivity()开始,最终都会调用startActivityForResult() 在该方法里面会调用Instrumentation. ...

  3. ios学习之路:Xcode+swift+打包ipa一步一坑记录

    咳咳,作为公司的Android开发(兼java接口开发,兼软件测试,兼运维……)由于公司ios开发小伙伴离我而去,ios的app出了问题,急需处理.于是领导决定由我来处理一下.就是用证书重新打包的事儿 ...

  4. Racket 命令行方式安装 collection

    最近在学习 SICP,里面用的 Lisp 系列的 Scheme.OS X 上要配置Scheme环境. Racket 完整的包要 110 M,mini 版只要10M.我只需要简单的命令行操作,显然选mi ...

  5. php有必要用swoole吗

    在 Swoole 官网的自我介绍是“面向生产环境的 PHP 异步网络通信引擎”,首先 Swoole 它是一个网络应用的开发工具,它支持 Http.TCP.UDP.WebSocket. Swoole 和 ...

  6. 解决JRebel对myBatis Mapper 失效的问题

    解决JRebel对myBatis Mapper 失效的问题 在之前的文章中介绍了JRebel这个插件的使用和优势,虽然它对配置文件的改动的热更新是生效的,但是mybatis的mapper文件的改动却无 ...

  7. 每天进步一点点----JS之比较运算符易错点

    1.字符串的比较 字符串也是可以比较的,字符串比较的asc码顺序:asc有128位,由7位二进制数表示,每个数对应的是一个字符.ASC码有ASC码1,由7位二进制1数表示:ASC2码又8位二进制数表示 ...

  8. 初识NLP 自然语言处理

    接下来的一段时间,要深入研究下自然语言处理这一个学科,以期能够带来工作上的提升. 学习如何实用python实现各种有关自然语言处理有关的事物,并了解一些有关自然语言处理的当下和新进的研究主题. NLP ...

  9. Java生鲜电商平台-服务化后的互联网架构实战(针对生鲜电商小程序或者APP)

    Java生鲜电商平台-服务化后的互联网架构实战(针对生鲜电商小程序或者APP) “微服务架构”的话题非常之火,很多朋友都在小窗我,说怎么做服务化?解答“怎么做”之前,先得了解“为什么做”. 画外音:做 ...

  10. MySQL修改数据库时区

    --查看数据库时区设置mysql> show variables like "%time_zone%"; +------------------+--------+ | Va ...