
长期从事Windows和linux应用程序开发,系统开发,驱动程序开发以及基于.net平台的软件开发;擅长面向对象程序设计、数据库设计、应用与开发;
来自博客: http://blog.csdn.net/kesaihao862/article/details/7332528 这篇文章介绍在LINUX下进行C语言编程所需要的基础知识。在这篇文章当中,我们将会学到以下内容: 源程序编译 Makefile的编写 程序库的链接 程序的调试 头文件和系统求助 1.源程序的编译 在Linux下面,如果要编译一个C语言源程序,我们要使用GNU的gcc编译器。 下面我们以一个实例来说明如何使用gcc编译器。 假设我们有下面一个非常简单的源程序(hello.c): int main(int argc,char **argv) { printf("Hello Linux\n"); } 要编译这个程序,我们只要在命令行下执行: gcc -o hello hello.c gcc 编译器就会为我们生成一个hello的可执行文件。执行./hello就可以看到程序的输出结果了。命令行中 gcc表示我们是用gcc来编译我们的源程序,-o 选项表示我们要求编译器给我们输出的可执行文件名为hello 而hello.c是我们的源程序文件。 gcc编译器有许多选项,一般来说我们只要知道其中的几个就够了。 -o选项我们已经知道了,表示我们要求输出的可执行文件名。 -c选项表示我们只要求编译器输出目标代码,而不必要输出可执行文件。 -g选项表示我们要求编译器在编译的时候提供我们以后对程序进行调试的信息。 知道了这三个选项,我们就可以编译我们自己所写的简单的源程序了,如果你想要知道更多的选项,可以查看gcc的帮助文档,那里有着许多对其它选项的详细说明。 2.Makefile的编写 假设我们有下面这样的一个程序,源代码如下: /* main.c */ #include "mytool1.h" #include "mytool2.h" int main(int argc,char **argv) { mytool1_print("hello"); mytool2_print("hello"); } /* mytool1.h */ #ifndef _MYTOOL_1_H #define _MYTOOL_1_H void mytool1_print(char *print_str); #endif /* mytool1.c */ #include "mytool1.h" void mytool1_print(char *print_str) { printf("This is mytool1 print %s\n",print_str); } /* mytool2.h */ #ifndef _MYTOOL_2_H #define _MYTOOL_2_H void mytool2_print(char *print_str); #endif /* mytool2.c */ #include "mytool2.h" void mytool2_print(char *print_str) { printf("This is mytool2 print %s\n",print_str); } 当然由于这个程序是很短的我们可以这样来编译 gcc -c main.c gcc -c mytool1.c gcc -c mytool2.c gcc -o main main.o mytool1.o mytool2.o 这样的话我们也可以产生main程序,而且也不时很麻烦。但是如果我们考虑一下如果有一天我们修改了其中的一个文件(比如说mytool1.c)那么我们 难道还要重新输入上面的命令?也许你会说,这个很容易解决啊,我写一个SHELL脚本,让她帮我去完成不就可以了。是的对于这个程序来说,是可以起到作用 的。但是当我们把事情想的更复杂一点,如果我们的程序有几百个源程序的时候,难道也要编译器重新一个一个的去编译? 为此,聪明的程序员们想出了一个很好的工具来做这件事情,这就是make。我们只要执行以下make,就可以把上面的问题解决掉。在我们执行make之 前,我们要先编写一个非常重要的文件。--Makefile。对于上面的那个程序来说,可能的一个Makefile的文件是: # 这是上面那个程序的Makefile文件 main:main.o mytool1.o mytool2.o gcc -o main main.o mytool1.o mytool2.o main.o:main.c mytool1.h mytool2.h gcc -c main.c mytool1.o:mytool1.c mytool1.h gcc -c mytool1.c mytool2.o:mytool2.c mytool2.h gcc -c mytool2.c 有了这个Makefile文件,不过我们什么时候修改了源程序当中的什么文件,我们只要执行make命令,我们的编译器都只会去编译和我们修改的文件有关的文件,其它的文件她连理都不想去理的。 下面我们学习Makefile是如何编写的。 在Makefile中也#开始的行都是注释行.Makefile中最重要的是描述文件的依赖关系的说明。一般的格式是: target:components TAB rule 第一行表示的是依赖关系。第二行是规则。 比如说我们上面的那个Makefile文件的第二行 main:main.o mytool1.o mytool2.o 表示我们的目标(target)main的依赖对象(components)是main.o mytool1.o mytool2.o 当倚赖的对象在目标修改后修改的话,就要去执行规则一行所指定的命令。就象我们的上面那个Makefile第三行所说的一样要执行 gcc -o main main.o mytool1.o mytool2.o 注意规则一行中的TAB表示那里是一个TAB键 Makefile有三个非常有用的变量。分别是$@,$^,$ $@--目标文件,$^--所有的依赖文件,$ 如果我们使用上面三个变量,那么我们可以简化我们的Makefile文件为: # 这是简化后的Makefile main:main.o mytool1.o mytool2.o gcc -o $@ $^ main.o:main.c mytool1.h mytool2.h gcc -c $ mytool1.o:mytool1.c mytool1.h gcc -c $ mytool2.o:mytool2.c mytool2.h gcc -c $ 经过简化后我们的Makefile是简单了一点,不过人们有时候还想简单一点。这里我们学习一个Makefile的缺省规则 .c.o: gcc -c $ 这个规则表示所有的 .o文件都是依赖与相应的.c文件的。例如mytool.o依赖于mytool.c这样Makefile还可以变为: # 这是再一次简化后的Makefile main:main.o mytool1.o mytool2.o gcc -o $@ $^ .c.o: gcc -c $ 好了,我们的Makefile 也差不多了,如果想知道更多的关于Makefile规则可以查看相应的文档。 3.程序库的链接 试着编译下面这个程序 /* temp.c */ #include int main(int argc,char **argv) { double value; printf("Value:%f\n",value); } 这个程序相当简单,但是当我们用 gcc -o temp temp.c 编译时会出现下面所示的错误。 /tmp/cc33Kydu.o: In function `main': /tmp/cc33Kydu.o(.text+0xe): undefined reference to `log' collect2: ld returned 1 exit status 出现这个错误是因为编译器找不到log的具体实现。虽然我们包括了正确的头文件,但是我们在编译的时候还是要连接确定的库。在Linux下,为了使用数学 函数,我们必须和数学库连接,为此我们要加入 -lm 选项。 gcc -o temp temp.c -lm这样才能够正确的编译。也许有人要问,前面我们用printf函数的时候怎么没有连接库呢?是这样的,对于一些常用的函数的实现,gcc编译器会自 动去连接一些常用库,这样我们就没有必要自己去指定了。有时候我们在编译程序的时候还要指定库的路径,这个时候我们要用到编译器的 -L选项指定路径。比如说我们有一个库在 /home/hoyt/mylib下,这样我们编译的时候还要加上 -L/home/hoyt/mylib。对于一些标准库来说,我们没有必要指出路径。只要它们在起缺省库的路径下就可以了。系统的缺省库的路径/lib /usr/lib /usr/local/lib 在这三个路径下面的库,我们可以不指定路径。 还有一个问题,有时候我们使用了某个函数,但是我们不知道库的名字,这个时候怎么办呢?很抱歉,对于这个问题我也不知道答案,我只有一个傻办法。首先,我 到标准库路径下面去找看看有没有和我用的函数相关的库,我就这样找到了线程(thread)函数的库文件(libpthread.a)。 当然,如果找不到,只有一个笨方法。比如我要找sin这个函数所在的库。 就只好用 nm -o /lib/*.so|grep sin>~/sin 命令,然后看~/sin文件,到那里面去找了。在sin文件当中,我会找到这样的一行libm-2.1.2.so:00009fa0 W sin 这样我就知道了sin在 libm-2.1.2.so库里面,我用 -lm选项就可以了(去掉前面的lib和后面的版本标志,就剩下m了所以是 -lm)。 如果你知道怎么找,请赶快告诉我,我回非常感激的。谢谢! 4.程序的调试 我们编写的程序不太可能一次性就会成功的,在我们的程序当中,会出现许许多多我们想不到的错误,这个时候我们就要对我们的程序进行调试了。 最常用的调试软件是gdb.如果你想在图形界面下调试程序,那么你现在可以选择xxgdb.记得要在编译的时候加入 -g选项.关于gdb的使用可以看gdb的帮助文件。由于我没有用过这个软件,所以我也不能够说出如何使用。不过我不喜欢用gdb.跟踪一个程序是很烦的 事情,我一般用在程序当中输出中间变量的值来调试程序的。当然你可以选择自己的办法,没有必要去学别人的。现在有了许多IDE环境,里面已经自己带了调试 器了。你可以选择几个试一试找出自己喜欢的一个用。 5.头文件和系统求助 有时候我们只知道一个函数的大概形式,不记得确切的表达式,或者是不记得着函数在那个头文件进行了说明。这个时候我们可以求助系统。 比如说我们想知道fread这个函数的确切形式,我们只要执行 man fread 系统就会输出着函数的详细解释的。和这个函数所在的头文件说明了。 如果我们要write这个函数的说明,当我们执行man write时,输出的结果却不是我们所需要的。 因为我们要的是write这个函数的说明,可是出来的却是write这个命令的说明。为了得到write的函数说明我们要用 man 2 write. 2表示我们用的write这个函数是系统调用函数,还有一个我们常用的是3表示函数是C的库函数。 记住不管什么时候,man都是我们的最好助手。
http://jingyan.baidu.com/article/20b68a88572a1c796cec6238.html
遍历获得一个实体类的所有属性名,以及该类的所有属性的值//先定义一个类: public class User { public string name { get; set; } public string gender { get; set; } public string age { get; set; } } //实例化类,并给实列化对像的属性赋值: User u = new User(); u.name = "ahbool"; u.gender = "男";//输出此类的所有属性名和属性对应的值 Response.Write(getProperties(u)); //输出结果为: name:ahbool,gender:男,age:, //遍历获取类的属性及属性的值:public string getProperties(T t){ string tStr = string.Empty; if (t == null) { return tStr; } System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length { return tStr; } foreach (System.Reflection.PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { tStr += string.Format("{0}:{1},", name, value); } else { getProperties(value); } } return tStr;} 转发自: http://www.cnblogs.com/Byrd/archive/2012/08/21/2649518.html
方法一 System.Net.WebClient WebClientObj = new System.Net.WebClient(); System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection(); PostVars.Add("A1","0"); PostVars.Add("A2","0"); PostVars.Add("A3","000"); try { byte[] byRemoteInfo = WebClientObj.UploadValues("http://www.lovezhao.com/vote.asp","POST",PostVars); //下面都没用啦,就上面一句话就可以了 string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo); //这是获取返回信息 richTextBox_instr.Text += sRemoteInfo; } catch {} 方法二、 string url = "网址"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); string s = "要提交的数据"; byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes (LoginInfo); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = requestBytes.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write(requestBytes,0,requestBytes.Length); requestStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default); string backstr = sr.ReadToEnd(); Response.Write(line); sr.Close(); res.Close(); 1. 创建httpWebRequest对象 HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。 WebRequest是获得一些列应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。所以我们的程序里面有一个对返回对象的类型进行测试的过程。 2. 初始化HttpWebRequest对象 这个过程提供一些http请求常用的属性:agentstring,contenttype等其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。很多认真设计的网站都会根据这个值来返回对用户浏览器特别优化过的代码。 3. 附加要POST给服务器的数据到HttpWebRequest对象 附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。 4. 读取服务器的返回信息 读取服务器返回的时候,要注意返回数据的encoding。如果我们提供的解码类型不对会造成乱码。比较常见的是utf-8和gb2312之间的混淆,据我测试,国内的主机一般都是gb2312编码的。一般设计良好的网站会把它编码的方式放在返回的http header里面,但是也有不少网站根本没有,我们只能通过一个对返回二进制值的统计方法来确定它的编码方式。 /// /// /// /// 地址 /// 方法 /// json参数 /// public static string WebServiceApp(string url, string method, string param) { //转换输入参数的编码类型,获取bytep[]数组 byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param); //初始化新的webRequst //1. 创建httpWebRequest对象 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method)); //2. 初始化HttpWebRequest对象 webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。) Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面 newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); //4. 读取服务器的返回信息 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string phpend = php.ReadToEnd(); return phpend; } 转自网址: http://www.cnblogs.com/wyBlog117/p/5308141.html
http://blog.csdn.net/lishehe/article/details/8257545
问题:如果在Access 中数据库操作时提示from子句语法错误原因:语句中某一单词为Access中的关键字。如:select * from user。其中user就是一关键字。解决:用中括号[]将其括起来。如:[user]即可。像Counter也是Access的关键字。所以给ACCESS命令表时要时刻注意不能与ACCESS的关键字重名。 转自: http://blog.csdn.net/lanpy88/article/details/7209867/
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace ConsoleApplication2 { class Program { public enum CMD_ERROR_TYPE { //解释出错 PARSE_ERROR = 1, //错误CMD BAD_CMD, } static void Main(string[] args) { string cmd = "5 FAIL 1\n"; if (IsServRespFailCMD(cmd)) ; Console.ReadLine(); } public static bool IsServRespFailCMD(string rcvedCMD) { Hashtable htFileCmd = new Hashtable(); string stdFileCmd = string.Empty; foreach (int e in Enum.GetValues(typeof(CMD_ERROR_TYPE))) { stdFileCmd = string.Format("5 FAIL {0}\n", e); htFileCmd.Add(stdFileCmd, e); } if (htFileCmd.ContainsKey(rcvedCMD)) return true; return false; } } }
//先拖一个label1到界面,然后在Paint事件里面复制代码 private void Form1_Paint(object sender, PaintEventArgs e) { Font f = label1.Font; Graphics g = e.Graphics; SizeF z = g.MeasureString(label1.Text, f);//关键 //为了验证是否为显示的字符串长度 g.DrawRectangle(new Pen(Color.Red), 0, 0, z.Width, z.Height); } 转自: http://zhidao.baidu.com/link?url=2CvDQybhANGwzVbdPA8hX5F0BzBcPf41NNOVBb5I_tuxgV9e5r3-Vn6sl7oPw6VjevYT99Tm3yYwDcMF1kh8y8aPCjspWmqgWCn1txcTGYO
private void SaveFileDialog(){ //string localFilePath, fileNameExt, newFileName, FilePath; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); //设置文件类型 saveFileDialog1.Filter = " txt files(*.txt)|*.txt|All files(*.*)|*.*"; //设置默认文件类型显示顺序 saveFileDialog1.FilterIndex = 2; //保存对话框是否记忆上次打开的目录 saveFileDialog1.RestoreDirectory = true; //点了保存按钮进入 if (saveFileDialog1.ShowDialog() == DialogResult.OK) { //获得文件路径 //localFilePath = saveFileDialog1.FileName.ToString(); //获取文件名,不带路径 //fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件路径,不带文件名 //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\")); //给文件名前加上时间 //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt; //在文件名里加字符 //saveFileDialog1.FileName.Insert(1,"dameng"); System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件 }}转自网址:http://blog.csdn.net/free4294/article/details/7048166参考网址:http://www.cnblogs.com/smile-wei/archive/2012/07/04/2575630.html
不能盲目将HTML中所有的图片转换成二进制来存储,当图片越来越大时,image的data域会变得非常大,从而导致无法通过data来读取图片。 图片数据读不出来的现象: 由于很多情况是不清楚图片的,处理HTML的图片问题,还是使用相对路径来处理。 附将图片转为data数据的方法: private string ReplaceFileSystemImages(string html) { var matches = Regex.Matches(html, @"]*?src\s*=\s*([""']?[^'"">]+?['""])[^>]*?>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline); foreach (Match match in matches) { string src = match.Groups[1].Value; src = src.Trim('\"'); if (File.Exists(src)) { var ext = Path.GetExtension(src); if (ext.Length > 0) { ext = ext.Substring(1); src = string.Format("'data:image/{0};base64,{1}'", ext, Convert.ToBase64String(File.ReadAllBytes(src))); html = html.Replace(match.Groups[1].Value, src); } } } return html; } 参考文献: http://zhidao.baidu.com/link?url=OLUlZr54BZR9dYyn4195D8n5CTyVB-VEjPVG4VMeHMFzMfp6zMm-LtxK188Yal9x2bNWEQRF-afUxiFhuZxvWq
public static string ByteArray2String(byte[] contentByte) { string result = string.Empty; if(contentByte != null) result = Encoding.GetEncoding("UTF-8").GetString(contentByte, 0, contentByte.Length); return result; } public static byte[] String2ByteArray(string documentText)//(Editor myEditor) { byte[] contentBytes = null; /*!!! myEditor.Html中的IMAGE是路径,BodyHtml中的是转换后byte[],但bodyhtml只包含body内的html, 取整个文件的html需要使用DocumentText */ if (string.IsNullOrWhiteSpace(documentText)) contentBytes = null; else contentBytes = Encoding.GetEncoding("UTF-8").GetBytes(documentText); return contentBytes; }
foreach (Control c in this.Controls) c.Enabled = false;参考网址:http://zhidao.baidu.com/link?url=T9wkzy_Mes2azMx8W9guZ0PYwvRJByicosVv8RICxq8020WRErVf5jZvKjZ5tPxxx6E49qYq-BaQXI3bQZYc__
public static ListCLocalTabStruct.ScreenLableItem> GetXmlLabelNameList(string fileFullName) { ListCLocalTabStruct.ScreenLableItem> listLabelItem = new ListCLocalTabStruct.ScreenLableItem>(); if (fileFullName.Equals(string.Empty)) return null; XmlDocument tmpDoc = new XmlDocument(); tmpDoc.Load(fileFullName); XmlNode rootNode = tmpDoc.SelectSingleNode("Controls"); XmlNodeList slblNodeList = null; if (rootNode.SelectSingleNode("SmartLabels") != null) slblNodeList = rootNode.SelectSingleNode("SmartLabels").ChildNodes; if (slblNodeList == null) return null; foreach (XmlNode xn0 in slblNodeList) { XmlElement xe = (XmlElement)xn0; CLocalTabStruct.ScreenLableItem lblItem = new CLocalTabStruct.ScreenLableItem(); lblItem.ItemName = xe.GetAttribute("Name"); lblItem.Text = xe.GetAttribute("Text"); listLabelItem.Add(lblItem); } listLabelItem.Sort(CompareObject); return listLabelItem; } public static int CompareObject(CLocalTabStruct.ScreenLableItem x, CLocalTabStruct.ScreenLableItem y) { int result = 0; result = y.ItemName.CompareTo(x.ItemName); return result; } 参考文献: http://blog.csdn.net/zhouqinghe24/article/details/8649521
效果图: 同时滚动和选中两个DGV的行。 关键代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; namespace SyncDgvs { public partial class Form1 : Form { public Form1() { InitializeComponent(); fillDatagridview(); } private void fillDatagridview() { dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); for (int i = 0; i 100;i++ ) { dataGridView1.Rows.Add(i,i, i); dataGridView2.Rows.Add(i,i, i); } } private void dataGridView1_Scroll(object sender, ScrollEventArgs e) { PropertyInfo verticalOffset = dataGridView2.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance); verticalOffset.SetValue(this.dataGridView2, dataGridView1.VerticalScrollingOffset, null); } private void dataGridView2_Scroll(object sender, ScrollEventArgs e) { PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance); verticalOffset.SetValue(this.dataGridView1, dataGridView2.VerticalScrollingOffset, null); } private void dataGridView2_MouseClick(object sender, MouseEventArgs e) { int iRow = dataGridView2.CurrentRow.Index; dataGridView1.ClearSelection(); dataGridView1.Rows[iRow].Selected = true; } private void dataGridView1_MouseClick(object sender, MouseEventArgs e) { int iRow = dataGridView1.CurrentRow.Index; dataGridView2.ClearSelection(); dataGridView2.Rows[iRow].Selected = true; } } } 工程代码: SyncDgvs.rar 参考文献: http://stackoverflow.com/questions/33174898/c-sharp-synchronize-scroll-of-two-datagridviews
需要在窗体增加imageList和listview控件,并把ListView控件的LargeImageList设置为imageList1 ListView控件显示图片的大小可以在imageList1控件中调整ImageSize属性,如果图片失真,可以设置imageList1控件的ColorDepth值为Depth32Bit. 窗体设计: 参考代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using EXCEL = Microsoft.Office.Interop.Excel; using WORD = Microsoft.Office.Interop.Word; namespace ImageListView { public partial class OfficeTextEditor : Form { private LanguageWizard mParentFrm; public OfficeTextEditor(LanguageWizard parentFrm) { InitializeComponent(); this.mParentFrm = parentFrm; fillListView_Word(); fillListView_Excel(); } private List mLViewWord_FileName = new List(); private void fillListView_Word() { DirectoryInfo dir = new DirectoryInfo(Application.StartupPath + @"\Word"); listViewWord.Items.Clear(); this.imageListWord.Images.Clear(); foreach (FileInfo d in dir.GetFiles()) { if (d.Name.EndsWith("_E.doc")) { mLViewWord_FileName.Add(d.FullName); } } for (int i = 0; i mLViewWord_FileName.Count; i++) { this.imageListWord.Images.Add(System.Drawing.Image.FromFile(dir + @"\WordItem.png")); this.listViewWord.Items.Add(System.IO.Path.GetFileName(mLViewWord_FileName[i]), i); this.listViewWord.Items[i].ImageIndex = i; this.listViewWord.Items[i].Name = mLViewWord_FileName[i]; } } private List mLViewExcel_FileName = new List(); private void fillListView_Excel() { DirectoryInfo dir = new DirectoryInfo(Application.StartupPath + @"\Excels"); listViewExcel.Items.Clear(); this.imageListExcel.Images.Clear(); foreach (FileInfo d in dir.GetFiles()) { if (d.Name.EndsWith("_E.xls")) { mLViewExcel_FileName.Add(d.FullName); } } for (int i = 0; i mLViewExcel_FileName.Count; i++) { this.imageListExcel.Images.Add(System.Drawing.Image.FromFile(dir + @"\ExcelItem.png")); this.listViewExcel.Items.Add(System.IO.Path.GetFileName(mLViewExcel_FileName[i]), i); this.listViewExcel.Items[i].ImageIndex = i; this.listViewExcel.Items[i].Name = mLViewExcel_FileName[i]; } } private void button1_Click(object sender, EventArgs e) { //this.mParentFrm.Show(); this.Close(); } private void listViewWord_MouseDoubleClick(object sender, MouseEventArgs e) { ListViewHitTestInfo info = listViewWord.HitTest(e.X, e.Y); if (info.Item != null) { } } private void listViewExcel_MouseDoubleClick(object sender, MouseEventArgs e) { ListViewHitTestInfo info = listViewExcel.HitTest(e.X, e.Y); if (info.Item != null) { EXCEL.Application eApp = new EXCEL.Application(); EXCEL.Workbook workBook = eApp.Workbooks.Open(info.Item.Name); EXCEL.Worksheet workSheet = eApp.ActiveSheet; try { eApp.Visible = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { /* 关掉任务管理器中的进程EXCEL/WORD的关键代码 */ System.Runtime.InteropServices.Marshal.ReleaseComObject(eApp); System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); eApp = null; workBook = null; workSheet = null; GC.Collect(); } } } } } 运行效果: 参考网址: http://www.cnblogs.com/hfzsjz/p/3929131.html
ListView没有Item的双击事件,只能通过变通的方法得到,以下是我的变通方法 private void listView右侧_MouseDoubleClick( object sender , MouseEventArgs e ) { ListViewHitTestInfo info = listView右侧.HitTest (e.X , e.Y); if( info.Item != null ) { MessageBox.Show (info.Item.Text); } }转发自:http://blog.sina.com.cn/s/blog_4b25b7d50100nu9a.html
如已绑定过数据源: DataTable dt = (dataGridView1.DataSource as DataTable) 如未绑定过数据源:public DataTable GetDgvToTable(DataGridView dgv) { DataTable dt = new DataTable(); // 列强制转换 for (int count = 0; count { DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString()); dt.Columns.Add(dc); } // 循环行 for (int count = 0; count { DataRow dr = dt.NewRow(); for (int countsub = 0; countsub { dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value); } dt.Rows.Add(dr); } return dt; } 转自网址: http://www.cnblogs.com/linji/archive/2012/10/11/2719471.html
在VS2008/VS2010中编写?如下代码: PrintDialog printDialog = new PrintDialog(); printDialog.ShowDialog(); 在??XP环境下,它可以正常显示出打印对话框。但在Windows 7 64位环境下,什么也显示不出来,也没有异常抛出。 将PrintDialog.?UseEXDialog属性设置为True,可显示出打印对话框。代码如下: PrintDialog printDialog = new PrintDialog(); printDialog.UseEXDialog = true; printDialog.ShowDialog(); 这是VS2008/2010的bug,并且此bug可能不会在VS2008/2010上被修复。 转自: http://blog.csdn.net/gui597651737/article/details/7897388
C#禁用numericUpDown控件鼠标中键滚轮消息响应numericUpDown_roadgain.MouseWheel += new MouseEventHandler(Num_DiscountAmount_MouseWheel);private void Num_DiscountAmount_MouseWheel(object sender, MouseEventArgs e){ HandledMouseEventArgs h = e as HandledMouseEventArgs; if (h != null) { h.Handled = true; }}参考:http://www.jb51.net/article/34559.htm
Libevent官网:http://libevent.org/ windows 7下编译: 编译环境: windows 7 + VS2010 (1)解压libevent到F:\libevent\libevent-2.0.21-stable (2)打开Microsoft visual studio 2010命令行工具 (3)修改以下三个文件,添加宏定义: 在以下3个文件开头添加“#define _WIN32_WINNT 0x0500” libevent-2.0.21-stable\event_iocp.c libevent-2.0.21-stable\evthread_win32.c libevent-2.0.21-stable\listener.c (4)使用VS命令提示工具编译: cd/d F:\libevent\libevent-2.0.21-stable nmake /f Makefile.nmake (5)编译结果: libevent_core.lib:All core event and buffer functionality. This library contains all the event_base, evbuffer, bufferevent, and utility functions. libevent_extras.lib:This library defines protocol-specific functionality that you may or may not want for your application, including HTTP, DNS, and RPC. libevent.lib:This library exists for historical reasons; it contains the contents of both libevent_core and libevent_extra. You shouldn’t use it; it may go away in a future version of Libevent. (6)VS2010下使用lib 新建一个VC++控制台项目: main代码: // LibeventTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include #include #include #include #ifndef WIN32 #include # ifdef _XOPEN_SOURCE_EXTENDED # include # endif #include #endif #include "event2/bufferevent.h" #include "event2/buffer.h" #include "event2/listener.h" #include "event2/util.h" #include "event2/event.h" #include static const char MESSAGE[] = "Hello, World!\n"; static const int PORT = 9995; static void conn_writecb(struct bufferevent *bev, void *user_data) { struct evbuffer *output = bufferevent_get_output(bev); if (evbuffer_get_length(output) == 0) { printf("flushed answer\n"); bufferevent_free(bev); } } static void conn_eventcb(struct bufferevent *bev, short events, void *user_data) { if (events & BEV_EVENT_EOF) { printf("Connection closed.\n"); } else if (events & BEV_EVENT_ERROR) { printf("Got an error on the connection: %s\n", strerror(errno));/*XXX win32*/ } /* None of the other events can happen here, since we haven't enabled * timeouts */ bufferevent_free(bev); } static void signal_cb(evutil_socket_t sig, short events, void *user_data) { struct event_base *base = (struct event_base *)user_data; struct timeval delay = { 2, 0 }; printf("Caught an interrupt signal; exiting cleanly in two seconds.\n"); event_base_loopexit(base, &delay); } static void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data) { struct event_base *base = (struct event_base *)user_data; struct bufferevent *bev; bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); if (!bev) { fprintf(stderr, "Error constructing bufferevent!"); event_base_loopbreak(base); return; } bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL); bufferevent_enable(bev, EV_WRITE); bufferevent_disable(bev, EV_READ); bufferevent_write(bev, MESSAGE, strlen(MESSAGE)); } int main(int argc, char **argv) { struct event_base *base; struct evconnlistener *listener; struct event *signal_event; struct sockaddr_in sin; #ifdef WIN32 WSADATA wsa_data; WSAStartup(0x0201, &wsa_data); #endif base = event_base_new(); if (!base) { fprintf(stderr, "Could not initialize libevent!\n"); return 1; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(PORT); listener = evconnlistener_new_bind(base, listener_cb, (void *)base, LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&sin, sizeof(sin)); if (!listener) { fprintf(stderr, "Could not create a listener!\n"); return 1; } signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base); if (!signal_event || event_add(signal_event, NULL) { fprintf(stderr, "Could not create/add a signal event!\n"); return 1; } event_base_dispatch(base); evconnlistener_free(listener); event_free(signal_event); event_base_free(base); printf("done\n"); return 0; } 环境配置: 项目下建一个Lib目录,将上面三个lib文件copy到该目录下。 新建一个Include目录,将F:\libevent\libevent-2.0.21-stable\include下的文件和文件夹copy到该目录下,F:\libevent\libevent-2.0.21-stable\WIN32-Code下的文件copy到该目录下,2个event2目录下的文件可合并一起。 项目属性设置: VC++目录: 包含目录,添加:F:\Projects\LibeventTest\LibeventTest\Include; 库目录,添加:F:\Projects\LibeventTest\LibeventTest\Lib; C/C++: 代码生成-->运行库:多线程调试 (/MTd)(Debug下),多线程 (/MT)(Release下) 连接器: 输入:ws2_32.lib;wsock32.lib;libevent.lib;libevent_core.lib;libevent_extras.lib; ws2_32.lib;wsock32.lib;是用来编译Windows网络相关的程序库。 编译,生成! 转自: http://www.cnblogs.com/luxiaoxun/p/3603399.html
C#使用printDocument1.Print打印时不显示正在打印对话框有两种方法 第一种,使用PrintController PrintController printController = new StandardPrintController(); printDocument1.PrintController = printController; printDocument1.Print(); 第二种,把窗体的TopMost设为True 转自网址: http://www.cnblogs.com/chendaoyin/p/3194011.html
private DateTime mLastClickTime; this.mLastClickTime = Convert.ToDateTime("2013-01-01 00:00:00.0000"); private void setPnlMouseDown_Handler(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { TimeSpan s = new TimeSpan(); s = System.DateTime.Now - mLastClickTime; // 毫秒级比较 if (s.Milliseconds 500) { setPnlMouseDoubleClick_Handler(sender, e); } else { this.mLastClickTime = DateTime.Now; } } }
1. 执行如下按钮事件 private void btnFormMax_Click(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; } else { this.WindowState = FormWindowState.Maximized; } } 窗体最大化时 非全屏 不会遮盖任务栏 此时this.FormBorderStyle 默认为 Sizable 2. 执行如下按钮事件 private void btnFormMax_Click(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; } else { this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; } } 窗体最大化时 会全屏 及遮盖任务栏 此时this.FormBorderStyle 为 None 不会显示窗体标题栏等相关 3. 执行如下按钮事件 private void btnFormMax_Click(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; } else { this.FormBorderStyle = FormBorderStyle.None; this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height); this.WindowState = FormWindowState.Maximized; } } 窗体最大化时 全屏 不会遮盖任务栏 此时this.FormBorderStyle 为 None 不会显示窗体标题栏等相关 设置全屏就是设置窗体的WindowState属性和FormWindowState属性,就像上面的这段网上找到的简单代码所示,但是实际过程中发现,单纯如此并不能控制好状态栏的显示,有时最大化了,设置了任务栏隐藏,却没有效果,实验之后总结如下: //1.最大化操作必须先FormBorderStyle.None 后FormWindowState.Maximized, // 否则将无法覆盖任务栏。 //2.如果已经FormWindowState.Maximized,则需要先设为非FormWindowState.Maximized 的状态, // 否则后面的FormWindowState.Maximized 将不起作用,违背了“.”的内容。 if (this.WindowState == FormWindowState.Maximized) { this.Hide(); this.WindowState = FormWindowState.Normal; } this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; this.Show(); 实际上,FormBorderStyle.None 状态也会影响Winform中用于获取屏幕可用范围等一系列属性的取值,如 Screen.PrimaryScreen.WorkingArea。 转自网址: http://blog.csdn.net/zhaoguiqun/article/details/5894062
转自网址: http://www.cnblogs.com/gnielee/archive/2010/07/02/wpf-print-sample.html 我的工程:WpfPrinter.rar
出自:http://www.cnblogs.com/dougua/archive/2007/07/03/804035.html 设置ResizeMode="NoResize"可去掉最大化和最小化按钮 但没法再拖曳改变窗体大小 WS_CLIPSIBLINGS: 0x04000000 WS_CLIPCHILDREN: 0x02000000 WS_VISIBLE: 0x10000000 WS_DISABLED: 0x08000000 WS_MINIMIZE: 0x20000000 WS_MAXIMIZE: 0x01000000 WS_CAPTION: 0x00C00000 WS_BORDER: 0x00800000 WS_DLGFRAME: 0x00400000 WS_VSCROLL: 0x00200000 WS_HSCROLL: 0x00100000 WS_SYSMENU: 0x00080000 WS_THICKFRAME: 0x00040000 WS_MINIMIZEBOX: 0x00020000 WS_MAXIMIZEBOX: 0x00010000 在主窗口的样式更改 最近做的软件中要求禁止最大化按钮,并且要求可以改变窗体的Size。调查后发现WPF窗体没有设置最大化按钮状态的属性。改变WindowStyle属性可以达到禁用最大化按钮的目的,但是同时也不能更改窗体的Size了。最后想到了使用Windows API改变按钮状态的方法。使用GetWindowLong可以得到当前按钮的状态。使用SetWindowLong可以设置按钮的状态。使用SetWindowPos进行界面的更新。下面是这几个API的声明。 [DllImport("user32.dll", EntryPoint = "GetWindowLong")] public static extern int GetWindowLong(IntPtr hwnd, int nIndex); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] public static extern int SetWindowLong(IntPtr hMenu, int nIndex, int dwNewLong); [DllImport("user32.dll")] private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);进行禁用后必须进行界面的刷新,否则禁用状态不会立即显示在界面上。 private void DisableMaxmizebox(bool isDisable) { int GWL_STYLE = -16; int WS_MAXIMIZEBOX = 0x00010000; int SWP_NOSIZE = 0x0001; int SWP_NOMOVE = 0x0002; int SWP_FRAMECHANGED = 0x0020; IntPtr handle = new WindowInteropHelper(this).Handle; int nStyle = GetWindowLong(handle, GWL_STYLE); if (isDisable) { nStyle &= ~(WS_MAXIMIZEBOX); } else { nStyle |= WS_MAXIMIZEBOX; } SetWindowLong(handle, GWL_STYLE, nStyle); SetWindowPos(handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED); }这个函数可以通过参数确定是否禁用。
在正则中,匹配任意字符,其实写法网上有很多,但因为各种软件或程序写法不支持等原因导致的问题,大家可以多研究。 今天在Java中想使用正则表达式来获取一段文本中的任意字符。于是很随意得就写出如下匹配规则: (.*) 结果运行之后才发现,无法获得换行之后的文本。于是查了一下手册,才发现正则表达式中,“.”(点符号)匹配的是除了换行符“\n”以外的所有字符。同时,手册上还有一句话:要匹配包括 '\n' 在内的任何字符,请使用像 '[.\n]' 的模式。于是我将正则表达式的匹配规则修改如下: ([.\n]*),当然,如果是在java程序中直接写到话,需要改为([.\\n]*) 结果再次运行程序,发现什么内容也取不到了。我百思不得其解,又将其修改为如下规则: ([.|\n]*) 以及 ([\n.]*) 结果还是不行,什么内容都取不到。看来点符号和换行符卯上劲了~ 然后上网一查,虽然没有查出上述规则到底是什么地方出问题了,但是查出了一个解决办法,经过一试,果然可以匹配包括换行符在内的任意字符,以下为正确的正则表达式匹配规则: ([\s\S]*) 同时,也可以用 “([\d\D]*)”、“([\w\W]*)” 来表示。 转自网址: http://www.jb51.net/article/19713.htm
Match matchB = Regex.Match("abcdaBCdefg", @"\Babcd\B", RegexOptions.IgnoreCase); Console.WriteLine(matchB.Value); Match matchBError = Regex.Match("abcdaBCdefg", @"\babcd\b", RegexOptions.IgnoreCase); Console.WriteLine("match error " + matchBError.Value); Match mathcb = Regex.Match("good bad regexsoso", @"\bbad\b", RegexOptions.IgnoreCase); Console.WriteLine(mathcb.Value); Match mathcbError = Regex.Match("good bad regexsoso", @"\Bad\B", RegexOptions.IgnoreCase); Console.WriteLine("match error" + mathcb.Value); 等验证。。。 得参考 http://zhengze.51240.com/ 参考文献: http://www.aspku.com/kaifa/cjc/80228.html http://www.bkjia.com/zzbds/1064741.html http://www.cnblogs.com/fqw1987815/archive/2010/09/28/1837488.html
注:本工程来codeproject WPF默认的IMAGE是无法让GIF文件动起来的。 下面为一种可以让GIF在WPF中动起来的办法。 关键还在AnimatedGIFControl.cs文件中。 /****************************** Module Header ******************************\ Module Name: AnimatedGIFControl.cs Project: CSWPFAnimatedGIF Copyright (c) Microsoft Corporation. The CSWPFAnimatedGIF demonstrates how to implement an animated GIF image in WPF. This source is subject to the Microsoft Public License. See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. All other rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Media.Imaging; using System.Windows.Threading; namespace CSWPFAnimatedGIF { public class AnimatedGIFControl : System.Windows.Controls.Image { private Bitmap _bitmap; // Local bitmap member to cache image resource private BitmapSource _bitmapSource; public delegate void FrameUpdatedEventHandler(); /// /// Delete local bitmap resource /// Reference: http://msdn.microsoft.com/en-us/library/dd183539(VS.85).aspx /// [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool DeleteObject(IntPtr hObject); /// /// Override the OnInitialized method /// protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.Loaded += new RoutedEventHandler(AnimatedGIFControl_Loaded); this.Unloaded += new RoutedEventHandler(AnimatedGIFControl_Unloaded); } /// /// Load the embedded image for the Image.Source /// void AnimatedGIFControl_Loaded(object sender, RoutedEventArgs e) { // Get GIF image from Resources if (Properties.Resources.ProgressIndicator != null) { _bitmap = Properties.Resources.ProgressIndicator; Width = _bitmap.Width; Height = _bitmap.Height; _bitmapSource = GetBitmapSource(); Source = _bitmapSource; } } /// /// Close the FileStream to unlock the GIF file /// private void AnimatedGIFControl_Unloaded(object sender, RoutedEventArgs e) { StopAnimate(); } /// /// Start animation /// public void StartAnimate() { ImageAnimator.Animate(_bitmap, OnFrameChanged); } /// /// Stop animation /// public void StopAnimate() { ImageAnimator.StopAnimate(_bitmap, OnFrameChanged); } /// /// Event handler for the frame changed /// private void OnFrameChanged(object sender, EventArgs e) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, new FrameUpdatedEventHandler(FrameUpdatedCallback)); } private void FrameUpdatedCallback() { ImageAnimator.UpdateFrames(); if (_bitmapSource != null) _bitmapSource.Freeze(); // Convert the bitmap to BitmapSource that can be display in WPF Visual Tree _bitmapSource = GetBitmapSource(); Source = _bitmapSource; InvalidateVisual(); } private BitmapSource GetBitmapSource() { IntPtr handle = IntPtr.Zero; try { handle = _bitmap.GetHbitmap(); _bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { if (handle != IntPtr.Zero) DeleteObject(handle); } return _bitmapSource; } } } 测试工程代码:Show GIF animation in WPF (CSWPFAnimatedGIF).rar
使用下面这个模板,往HTML中写入中文,可能会显示乱码: 要想在静态的HTML文件中显示中文,可以将上面的meta语句改为: 这里的GB2312表示简体中文,也可以设置为大字符集GBK。 ISO8859-1,通常叫做Latin-1。Latin-1包括了书写所有西方欧洲语言不可缺少的附加字符。 两句保存HTML文本到HTML文件的句子: dynamic doc = MyWebBrowser.doc; var htmlText = doc.documentElement.InnerHtml; File.WriteAllText(/*DialogBox.SaveFile()*/path, htmlText,Encoding.UTF8); File.WriteAllText(/*DialogBox.SaveFile()*/path, htmlText); 这一句由于没有指明编码方式,容易出现乱码。 File.WriteAllText(/*DialogBox.SaveFile()*/path, htmlText); 参考文献: http://zhidao.baidu.com/link?url=ffeReZr12iolJAJXN4D5YMkkwXKGynUDLfPfpF3XlSEkT9Yt4P0nJi3KQ397CYFBoF6CsZbK0YP_ajfRG0lhRa https://msdn.microsoft.com/zh-cn/library/ms143376.aspx
HTML画直线: 画空行: .......
如下图,想给Image添加一个Source Voice.png 按理说,在【1】处应该出现一个资源文件并且以相对路径表示,而现在【2】中出现的竟然是绝对路径! 什么原因? 检查一下解决方案下的[Recources/WeiXin],发现Voice.png已经在里面。 原因自明!需要将[Recources/WeiXin]里的Voice.png删除,再在Image/Source中打开,就会自动以相对路径方式添加资源。 !!!!!小小的资源文件也有不小的学问!
说明,这三个开源工程都是来自codeproject www.codeproject.com 1、TextControl TextControlSource.zip本案例实现Tab和Ctrl+S的办法: /// /// 根据反向回调调用窗体的方法 /// private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.Modifiers == Keys.Control && e.KeyCode == Keys.S) { if (this.Name.Equals("editorChild") && this.ParentForm is EditExamQuestion) ((EditExamQuestion)this.ParentForm).ChildNodeSave(); if (this.Name.Equals("editorRoot") && this.ParentForm is EditExamQuestion) ((EditExamQuestion)this.ParentForm).RootNodeSave(); if (this.Name.Equals("editorTopic") && this.ParentForm is EditExamQuestion) ((EditExamQuestion)this.ParentForm).EditorTopicSave(); } if (e.KeyData == Keys.Tab) Indent(); if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Tab) Outdent(); this.webBrowser1.Focus(); } 2、ZetaHtmlEditControl zetahtmleditcontrol-source.zip 3、FsRichTextBox FsRichTextBox.rar 说明: 前两个是基于WebBroswer来实现。FsRichTextBox是基于richtextbox,没有图片导入及编辑功能。 目前三个开源版本都无法实现行间距的设置。待进一点研究。
出现“试图吊销一个未注册的拖放目标”错误,如下图: 出现的情景是一个放置了HtmlEditor的Winform窗体。 后面分析是窗体内的timer_tick方法引发的: 当ParentForm==null即窗体都未生成时,timer拼命去操作ParentForm上的控件,就会出现错误。 代码稍作修改: 参考文献: http://www.cnblogs.com/domainblogs/archive/2009/04/02/1428369.html
WebBrowser可以将Web浏览器的常用功能:如编辑、获取文本、HTML等移动PC端的应用程序。使用户能够在您的窗体中导航网页。 WebBrowser本身的属性、方法并不能完美的获取含图片的html的文本。 图片在html中有两种表现形式: 一种是将图片完全转换为byte[],另一种是直接引入绝对路径。明显使用第一种方法将IMAGE以byte[]存储到DB中,在应用程序移动到别的电脑上使用时有很大优势;而使用绝对路径由于并没有把图片拷由过去则会找不到文件。 完成方法一,需要在WebBrowser寄存的父窗体中添加几个属性及转换方法: /// Get/Set the documents body as text. /// [Browsable(false)] public string BodyText { get { if (webBrowser1.Document != null && webBrowser1.Document.Body != null) { return webBrowser1.Document.Body.InnerText; } else return string.Empty; } set { Document.OpenNew(false); if (webBrowser1.Document.Body != null) webBrowser1.Document.Body.InnerText = HttpUtility.HtmlEncode(value); } } [Browsable(false)] public string Html { get { if (webBrowser1.Document != null && webBrowser1.Document.Body != null) { return webBrowser1.Document.Body.InnerHtml; } else return string.Empty; } set { Document.OpenNew(true); IHTMLDocument2 dom = Document.DomDocument as IHTMLDocument2; try { if (value == null) dom.clear(); else dom.write(value); } finally { dom.close(); } } } /// /// Get/Set the contents of the document Body, in html. /// [Browsable(false)] public string BodyHtml { get { if (webBrowser1.Document != null && webBrowser1.Document.Body != null) { string html = webBrowser1.Document.Body.InnerHtml; if (html != null) { html = ReplaceFileSystemImages(html); } return html; } else return string.Empty; } set { if (webBrowser1.Document.Body != null) webBrowser1.Document.Body.InnerHtml = value; } } 将HTML中的图片路径转换为byte[]存储到html中的方法: private string ReplaceFileSystemImages(string html) { var matches = Regex.Matches(html, @"]*?src\s*=\s*([""']?[^'"">]+?['""])[^>]*?>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline); foreach (Match match in matches) { string src = match.Groups[1].Value; src = src.Trim('\"'); if (File.Exists(src)) { var ext = Path.GetExtension(src); if (ext.Length > 0) { ext = ext.Substring(1); src = string.Format("'data:image/{0};base64,{1}'", ext, Convert.ToBase64String(File.ReadAllBytes(src))); html = html.Replace(match.Groups[1].Value, src); } } } return html; } 参考文献: https://msdn.microsoft.com/zh-cn/library/system.windows.forms.webbrowser(v=vs.110).aspx
WINFORM工程引用mshtml.dll时,如果选择【嵌入互操作类型True】,下面的switch语句就会报错: 而将它设置为False,就没事!!什么情况? 什么是嵌入互操作类型? 现在可以使用 COM 互操作程序集,而不要求该程序集在运行时必须存在。目的是减轻将 COM 互操作程序集与您的应用程序一起部署的负担。您通过将引用上的“嵌入式互操作类型”属性设置为 true,告诉编译器为您将互操作类型嵌入到 Visual Studio 中。 1.”嵌入互操作类型”中的嵌入就是引进、导入的意思,类似于c#中using,c中include的作用,目的是告诉编译器是否要把互操作类型引入。 2.“互操作类型”实际是指一系列Com组件的程序集,是公共运行库中库文件,类似于编译好的类,接口等。 3.“嵌入互操作类型”设定为true,实际上就是不引入互操作集(编译时候放弃Com程序集),仅编译用户代码的程序集。 而设定为false的话,实际就是需要从互操作程序集中获取 COM 类型的类型信息。 参考文献: https://msdn.microsoft.com/zh-cn/library/dd997297 http://www.cnblogs.com/pnljs/archive/2012/02/20/2359313.html
C# Http下载指定文件存储到特定目录,下面是标准用法代码: /// /// Http下载文件:下载指定文件存储到特定目录 /// public static string HttpDownloadFile(string remoteUrl) { // 设置参数 HttpWebRequest request = WebRequest.Create(remoteUrl) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); string localPath = AppDomain.CurrentDomain.BaseDirectory + @"QRCode\MyQRCode.jpg"; //创建本地文件写入流 Stream stream = new FileStream(localPath, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } stream.Close(); responseStream.Close(); return localPath; } remoteUrl值说明: remoteUrl的值举例 https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFf8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL00wT1RpemZsRGc5M2tfTUpXV3V2AAIErEv7VgMEAAAAAA== 上面的URL值放到浏览器是可以直接打开文件的: 运行效果: 参考文献: http://www.jb51.net/article/57068.htm
1、下面这个三角形图标称为: RibbonApplicationMenu 在Ribbon控件的ApplicationMenu中被捆绑。可通过下面的菱形去除 或者直接设置为Hidden 2、实现下面的鼠标划过效果 可以没有RibbonGroup或RibbonTab,但一定要有ribbon:Ribbon。不然会出现鼠标划过按钮时,快捷键丝毫不变化,但事件却被触发的情况。 3、SmallImageSource和LargeImageSource Ribbon是有SmallImageSource和LargeImageSource这两项区别的。如果你要导入分辨率较大的图得用LargeImageSource,相反用SmallImageSource。 如果用LargeImageSource导入小图,就会出现小脚穿大鞋的状态:十分模糊。 以上为WPF RIBBON布局设计的常见注意问题。 4、很多时间一些父容器内的控件总是歪歪斜斜,很难调整。 这时候可以就要注意把相关父容器中的Margin、Height、Width等通通撤掉再试。
WPF Windows启动时 经验证,就是下面的d:DesignHeight="405" d:DesignWidth="968" 引发!去掉这两句即可。 DesignHeight DesignWidth是什么作用? 这个说法有些奇怪,不想深究!!!! 参考文献: http://www.wpftutorial.net/DesigntimeVsRuntime.html
使用一些开源工程,出现下面问题: RIBBON?是什么玩意? WPF Ribbon Control 控件库,开发出类似Office 2007 样式的Ribbon 工具栏。 一、下载安装相关插件并安装: https://www.microsoft.com/en-us/download/details.aspx?id=11877下载插件:Microsoft Ribbon for WPF.msi 安装完成后,在下面目录可以看到相关文件: C:\Program Files (x86)\Microsoft Ribbon for WPF MicrosoftRibbonForWPFSourceAndSamples中的精彩案例: 二、借用第三方的RIBBON文件出现的问题分析 解决方案: 参考文献: http://www.cnblogs.com/gnielee/archive/2010/08/04/microsoft-ribbon-for-wpf-rtm.html https://www.microsoft.com/en-us/download/details.aspx?id=11877
ToggleButton和Setter组成WPF的三态控件有时候较为实用。 ToggleButton就像拨动开关一样,把开关拨到一个位置,灯亮了;把开关拨到别一个位置,灯灭了。ToggleButton也是这样,按一下,其IsChecked属性变为True;再按一下,其IsChecked属性变为False。有时,我们需要维持三个状态,这时我们把IsThreeState属性设为True。在IsThreeState属性设为True时,IsChecked的属性值可能取三个值:True,False,Null,ToggleButton中的事件如下: Checked:当IsChecked为True时,产生该事件。 UnChecked:当IsChecked为False时,产生该事件。 Indeterminate:当IsChecked为Null时,产生该事件。 一般不直接创建创建ToggleButton实例,而是使用其派生类:CheckBox和RadioButton 三态控件常使用Command属性实现内置的功能处理,而避免编写对应的态事件处理方法。 下面为一个典型的用法: ToggleButton x:Name="BulletsButton" Command="EditingCommands.ToggleBullets" CommandTarget="{Binding ElementName=TextBox}" ToolTip="Bullets" Template="{StaticResource FlatToggleButtonControlTemplate}" Margin="0,1,0,1" Click="OnListButtonClick"> Image Source="Images\listbullets.png" Stretch="None" SnapsToDevicePixels="True" /> /ToggleButton> Command="EditingCommands.ToggleItalic" CodeProject源码参考: SourceCode.zip 参考: http://www.th7.cn/Program/WPF/201407/250250.shtml
WPF可以直接在控件上捆绑一些常用的命令如复制、粘贴、剪贴、撤销、恢复,通过指定目标控件直接生效。 相当方便,不用使用命令控制。 1、设计器直接控件跟ApplicationCommands命令捆绑: 2、捆绑命令响应的控件 在【应用数据绑定】中找到要响应命令的控件 3、控件设置内置样式(静态资源) 下面为一些较好的BUTTON等样式的控件模板,将其放到XAML文件中即成为StaticResources UserControl.Resources> !-- Flat Button --> ControlTemplate x:Key="FlatButtonControlTemplate" TargetType="{x:Type Button}"> Border x:Name="OuterBorder" BorderBrush="Transparent" BorderThickness="1" CornerRadius="2"> Border x:Name="InnerBorder" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" CornerRadius="2"> ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" Margin="{TemplateBinding Padding}" /> /Border> /Border> ControlTemplate.Triggers> Trigger Property="IsMouseOver" Value="True"> Setter TargetName="OuterBorder" Property="BorderBrush" Value="#FF7CA0CC" /> Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FFE4EFFD" /> Setter TargetName="InnerBorder" Property="Background" Value="#FFDAE7F5" /> /Trigger> Trigger Property="IsPressed" Value="True"> Setter TargetName="OuterBorder" Property="BorderBrush" Value="#FF2E4E76" /> Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FF116EE4" /> Setter TargetName="InnerBorder" Property="Background" Value="#FF3272B8" /> /Trigger> /ControlTemplate.Triggers> /ControlTemplate> !-- Flat Toggle Button --> ControlTemplate x:Key="FlatToggleButtonControlTemplate" TargetType="{x:Type ToggleButton}"> Border x:Name="OuterBorder" BorderBrush="Transparent" BorderThickness="1" CornerRadius="2"> Border x:Name="InnerBorder" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" CornerRadius="2"> ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" Margin="{TemplateBinding Padding}" /> /Border> /Border> ControlTemplate.Triggers> Trigger Property="IsMouseOver" Value="True"> Setter TargetName="OuterBorder" Property="BorderBrush" Value="#FF7CA0CC" /> Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FFE4EFFD" /> Setter TargetName="InnerBorder" Property="Background" Value="#FFDAE7F5" /> /Trigger> Trigger Property="IsPressed" Value="True"> Setter TargetName="OuterBorder" Property="BorderBrush" Value="#FF2E4E76" /> Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FF116EE4" /> Setter TargetName="InnerBorder" Property="Background" Value="#FF3272B8" /> /Trigger> Trigger Property="IsChecked" Value="True"> Setter TargetName="OuterBorder" Property="BorderBrush" Value="#FFFFC00A" /> Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FFFFDE7F" /> Setter TargetName="InnerBorder" Property="Background" Value="#FFFFD458" /> /Trigger> /ControlTemplate.Triggers> /ControlTemplate> /UserControl.Resources> 控件调用上述模板来美化外观: 案例效果: 参考工程:SourceCode.zip
Regex类表示.NET Framework 正则表达式引擎。可用于快速分析大量的文本来查找特定的字符模式 ;若要提取,编辑、 替换或删除文本子字符串 ;并将提取的字符串添加到集合以生成报告。 一、正则表达式类Regex类用法 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace TestRegex { class Program { static void Main(string[] args) { replaceString(); getFieldValue(); getSpecifyValue(); judgeJSONString(); Console.ReadLine(); } static void replaceString() { string line = "ADDR=1234;NAME=ZHANG;PHONE=6789"; Regex reg = new Regex("NAME=(.+);"); string modified = reg.Replace(line, "NAME=WANG;"); Console.WriteLine(modified + "\n"); } /// /// 抽取某些特征数据 /// /// static void getFieldValue() { string content = "src=C:\\Users\\Administrator\\Desktop\\WeixinImg\\08.jpg\r\nDOS图片1\r\nsrc=C:\\Users\\Administrator\\Desktop\\WeixinImg\\10.jpg\r\nDOS图片2\r\n"; Regex reg = new Regex(@"src=(.+)"); List urlList = new List(); /* 遍历源串,取出所有的src=后面的地址 */ foreach (Match re in reg.Matches(content)) { Console.WriteLine("{0}", re.Groups[1].Value); } } static void getSpecifyValue() { string line = "lane=1;speed=30.3mph;acceleration=2.5mph/s"; Regex reg = new Regex(@"speed\s*=\s*([\d\.]+)\s*(mph|km/h|m/s)*"); Match match = reg.Match(line); Console.WriteLine(match + "\n"); } static void judgeJSONString() { string testData = "{\"url\":\"http:\\/\\/mmbiz.qpic.cn\\/mmbiz\\/1Y1o1ZhehiaBibw7nnxg20e67JrhWsWOmEYZz9TKah84LlNZGr89iclu965hdWkibQJ5S51icvH4nHrmnBwpEvbibr0w\\/0\"}"; Regex rgx = new Regex(@"\{.*\}", RegexOptions.IgnoreCase); if (rgx.IsMatch(testData)) { testData = rgx.Match(testData).Value; Console.WriteLine("string is JSON!"); Console.WriteLine(testData); } else Console.WriteLine("string isn't JSON!"); } } } 二、正则表达式符号模式: 说明: 由于在正则表达式中“ \ ”、“ ? ”、“ * ”、“ ^ ”、“ $ ”、“ + ”、“(”、“)”、“ | ”、“ { ”、“ [ ”等字符已经具有一定特殊意义,如果需要用它们的原始意义,则应该对它进行转义,例如希 望在字符串中至少有一个“ \ ”,那么正则表达式应该这么写: \\+ 。 参考文献: http://www.studyofnet.com/news/297.html https://msdn.microsoft.com/zh-cn/library/system.text.regularexpressions.regex(v=vs.110).aspx
WPF: private string GetText(RichTextBox richTextBox) { TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); return textRange.Text; } ST: var run = describeRichTextBox.Selection.Start.Parent as Run; if (run != null) { string str = run.Text; } 转自网址http://blog.csdn.net/wushang923/article/details/11048645
下面两个方法按理说都是可以修改Winform的label文本颜色的。 但是方法二有时候的无效的,这种情况必须使用方法一。方法一: this.label1.ForeColor = System.Drawing.Color.FromName("#AECC33");方法二:this.label1.ForeColor = Color.GreenYellow;参考:http://blog.csdn.net/xianfajushi/article/details/4745120http://jingyan.baidu.com/article/425e69e69690f0be15fc168a.html
string aa = "你好欢迎你来到博客园";byte[] byteArry = new byte[0];byteArry = System.Text.Encoding.Default.GetBytes(aa);string str = System.Text.Encoding.Default.GetString(byteArry);Response.Write(str); 转自博客: http://www.cnblogs.com/Lucky2007/archive/2008/04/01/1132795.html
VS2010有时候莫名出现下面问题: 未能解析目标框架“.NETFramework,Version=v4.0”的 mscorlib 错误 相关的工程出现这个问题,可能是使用同步盘同步的引起的。因为在下每次同步时都会将工程清理一下两天同步。于是试着将本地工程先清理,再重新生成,就OK了。更深入的原因分析见参考文献。 参考文献: http://www.ithao123.cn/content-8215587.html
{\"errcode\":40130,\"errmsg\":\"invalid openid list size, at least two openid hint: [3nQPea0245age6]\ 上述错误是因为群发的用户数用户有两个或两个以上,由于本公众号只有一个关注用户,所有报错。 可以在获取OPenID时作个判断,只有一个openid时加个空行处理。 /// /// 获取关注者OpenID集合 /// public static List GetOpenIDs(string access_token) { List result = new List(); List openidList = GetOpenIDs(access_token, null); result.AddRange(openidList); while (openidList.Count > 0) { openidList = GetOpenIDs(access_token, openidList[openidList.Count - 1]); result.AddRange(openidList); } /* 若只有一个OpenID,加一空ID,避免“invalid openid list size, at least two openid hint”*/ if (result.Count == 1) result.Add(""); return result; }
有时候得到的原图片,边缘不合用,想要在原图基础上向两边扩展一些。 可以用PS的裁剪工具实现。 用裁剪功能选中图片,在顶端往上拉: 拉出一定的空间 再按下Enter键,出现空白区域 上面的空白区就可以写文字、填充颜色了。 参考文献: http://jingyan.baidu.com/article/72ee561ab15733e16138df07.html
1、快速画横线竖线 选择画笔工具,按住shift键横拉得横线;按住shift键竖拉得竖线; 2、画斜线 上面方法画不了斜线,画斜线得用直线工具 参考文献: http://jingyan.baidu.com/article/d169e186a90529436711d871.html