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. Logstash组件详解(input、codec、filter、output)

    logstash组件详解 logstash的概念及特点. 概念:logstash是一个数据采集.加工处理以及传输(输出)的工具. 特点: - 所有类型的数据集中处理 - 不同模式和格式数据的正常化 - ...

  2. C#中使用Path、Directory、Split、Substring实现对文件路径和文件名的常用操作实例

    场景 现在有一个文件路径 E:\\BTSData\\2019-11\\admin_20180918_1_1_2 需要获取最后的文件名admin_20180918_1_1_2 需要获取文件的上层目录20 ...

  3. linux 系统账户 和 普通账户 的区别

    最近使用 useradd -r 选项进行创建账户,用于测试,对-r 选项不是很明白,下面记录一些调研的过程: -r, --system Create a system account. System ...

  4. 基于XML的开发

    基于XML的开发 1.定义一个切面类 /** * Created by zejian on 2017/2/20.*/ public class MyAspectXML { public void be ...

  5. Spring Boot Request method DELETE not supported

    1: 开启HiddenHttpMethodFilter 最新版本的spring boot 默认不开启 restful 分割api @Bean @ConditionalOnMissingBean({Hi ...

  6. Python高级特性——列表生成式(list Comprehensions)

    List Comprehensions 即列表生成式,是Python内置的强大的用来生成列表list的生成式. 简单菜: >>> l = list(range(2,13)) > ...

  7. C# 委托汇总

    委托汇总以及遗留问题: using System; using System.Collections.Generic; using System.Linq; using System.Text; us ...

  8. python基础(36):pymysql模块

    1. pymysql模块 在使用pymysql模块前需要学习数据库MySQL:<MySQL基础>. 1.1 pymysql的下载和使用 看完MySQL基础,我们都是通过MySQL自带的命令 ...

  9. VS2017创建的单元测试不支持顺序测试

      问题:使用IDE创建的单元测试项目,标准引用是,导致不能添加顺序测试,复制其它项目的顺序测试文件进行编辑时,也会提示基于MSTest V2的测试不能用于顺序测试     解决办法: 移除自带的NU ...

  10. django之跨站请求伪造csrf

    目录 跨站请求伪造 csrf 钓鱼网站 模拟实现 针对form表单 ajax请求 csrf相关的两个装饰器 跨站请求伪造 csrf 钓鱼网站 就类似于你搭建了一个跟银行一模一样的web页面 , 用户在 ...