Visual C#.NET精彩编程实例集锦
0001:
如何使用错误提醒控件:
●控件名:ErrorProvider
●设置错误提醒:(当鼠标离开输入文本框时,如果输入的字符串长度小于5则提示)
private void textBox1_MouseLeave(object sender, System.EventArgs e)
{
if(this.textBox1.Text.Trim().Length <= 5)
{
errorProvider1.SetError(this.textBox1,"必须输入5位以上长度的字符串");
}
}
●取消错误提醒:(当鼠标进入输入文本框区域的时候发生)
private void textBox1_MouseEnter(object sender, System.EventArgs e)
{
errorProvider1.Dispose();
}
----------------------------------------------------------------------------------------------------
0002:
信息提示框的使用:
●控件名:MessageBox
●对用户选择判断:
DialogResult temp = MessageBox.Show(this,"用户输入错误,是否从新输入?","提示",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
switch(temp)
{
case DialogResult.Retry:
//
break;
case DialogResult.Cancel:
//
break;
}
----------------------------------------------------------------------------------------------------
0003:
如何使用信息提示控件:
●控件名:ToolTip
●提示信息:(多行提示信息的情况,@)
this.toolTip1.SetToolTip(this.textBox1,@"1,请输入数字
2,请输入数字
3,请输入数字
4,请输入数字");
●提示信息:(多行提示信息的情况,无@)
this.toolTip1.SetToolTip(this.textBox1,"1,请输入数字\n2,请输入数字\n3,请输入数字\n4,请输入数字");
----------------------------------------------------------------------------------------------------
0004:
如何使用菜单控件:
●控件名:MainMenu
●横线:输入一个"-",就会编程横线
●快捷键:在菜单名称中,"&"符号后面的字母代表了菜单的快捷键(Ctrl+字符)
●切换显示菜单前面被选中的小对勾:
private void menuItem2_Click(object sender, System.EventArgs e)
{
this.menuItem2.Checked = !this.menuItem2.Checked;
}
●如果设置menuItem2的RadioChecked属性为true,则会显示一个小黑点,而不是对勾,然后通过算法实现互
斥选择
----------------------------------------------------------------------------------------------------
0005:
如何使用工具栏控件:
●控件名:ToolBar
●添加按钮:单击Buttons属性
●单击的实现:
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
ToolBarButton temp = e.Button;
if(temp == this.toolBarButton1)
{
MessageBox.Show("1");
}
else if(temp == this.toolBarButton2)
{
MessageBox.Show("2");
}
else if(temp == this.toolBarButton3)
{
MessageBox.Show("3");
}
}
●注意:不能使用switch来进行选择判断
●ToolBar上的图标可以使用ImageList控件来设置
●在Buttons属性中添加按钮时,按钮还可以添加下拉菜单,DropDownMenu。添加的是ContextMenu控件,并且
设置其Style属性为DropDownButton。不要添加主菜单的DropDownMenu属性。
----------------------------------------------------------------------------------------------------
0006:
打开文件控件:
●控件名:OpenFileDialog
●举例:
//this.openFileDialog1.Filter = "文本文件(*.txt)|*.txt|文本文件(*.doc)|*.doc";
//this.openFileDialog1.Filter = "文本文件|*.txt;*.doc";
//this.openFileDialog1.Filter = "Jpeg|*.jpg;*jpeg|Tif|*.tif;*tiff|All files|*.*";
this.openFileDialog1.ShowDialog();
String str = this.openFileDialog1.FileName;
----------------------------------------------------------------------------------------------------
0007:
如何使用状态栏控件:
●控件名:StatusBar
●首先要设置StatusBar的ShowPanels的属性为真,然后设置其Panels属性
●举例:(显示鼠标的坐标)
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.statusBarPanel1.Text = Cursor.Position.X + " " + Cursor.Position.Y;
}
----------------------------------------------------------------------------------------------------
0008:
e.KeyCode:可以用于判断文本框等输入的内容是字符还是数字
private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
label1.Text = e.KeyCode.ToString();
}
----------------------------------------------------------------------------------------------------
0009:
如何使用托盘控件:
●控件名:NotifyIcon
●NotifyIcon可以设置右键菜单,右键菜单是ContextMenu控件
----------------------------------------------------------------------------------------------------
0010:
如何使用树状视图控件:
●控件名:TreeView
●举例:
TreeNode newNode1 = new TreeNode("根节点1",0,0);
TreeNode newNode2 = new TreeNode("根节点2",0,0);
TreeNode newNode3 = new TreeNode("根节点3",0,0);
TreeNode newNode31 = new TreeNode("子节点31",0,0);
TreeNode newNode32 = new TreeNode("子节点32",0,0);
TreeNode newNode33 = new TreeNode("子节点33",0,0);
this.treeView1.Nodes.Add(newNode1);
this.treeView1.Nodes.Add(newNode2);
this.treeView1.Nodes.Add(newNode3);
newNode3.Nodes.Add(newNode31);
newNode3.Nodes.Add(newNode32);
newNode3.Nodes.Add(newNode33);
newNode3.Expand();//展开子节点
this.treeView1.Select();
●选择某一个节点:
this.treeView1.SelectedNode = this.treeView1.Nodes[1];
this.treeView1.Select();
----------------------------------------------------------------------------------------------------
0011:
如何使用列表视图控件:
●控件名:ListView
●注意:应该把View属性改为Details
●举例:
private void Form1_Load(object sender, System.EventArgs e)
{
int i = this.listView1.Items.Count;
string[] s1 = {"张三","28岁","男"};
this.listView1.Items.Insert(i,new ListViewItem(s1));
string[] s2 = {"李四","22岁","女"};
this.listView1.Items.Insert(i,new ListViewItem(s2));
string[] s3 = {"马六","26岁","男"};
this.listView1.Items.Insert(i,new ListViewItem(s3));
}
----------------------------------------------------------------------------------------------------
0012:
如何使用窗体分隔控件:
●控件名:Splitter
●使用顺序:
(1)拖放一个RichTextBox控件
(2)设置其Dock为Bottom
(3)拖放一个Splitter控件
(4)设置其Dock为Bottom
●注意:如果还有其它控件需要拖动,需要再增加Splitter控件
----------------------------------------------------------------------------------------------------
0013:
如何获取程序文件信息:
●获取当前程序可执行文件的路径信息:Application.ExecutablePath.ToString()
●获取当前程序可执行文件的文件夹路径信息:Application.StartupPath.ToString()
●获取任意文件的信息:
System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath);//输入fileName
MessageBox.Show(info.FileName);
●返回文件根目录信息:string str = System.IO.Directory.GetDirectoryRoot(@"C:\汉化\汉化说明.txt");
●返回文件的父目录信息:System.IO.DirectoryInfo info = System.IO.Directory.GetParent(@"C:\汉化\汉化说明.txt");
●返回当前程序所在的文件夹:string str = System.IO.Directory.GetCurrentDirectory();
●获取指定文件夹下的所有信息:string[] str = System.IO.Directory.GetFiles(@"C:\汉化");
●如何使用ListBox控件显示信息:
string[] str = System.IO.Directory.GetFiles(@"C:\汉化");
this.listBox1.Items.AddRange(str);
●如何获取指定文件的文件属性:System.IO.FileAttributes fa = System.IO.File.GetAttributes(@"C:\汉化\汉化说明.txt");
●设置指定文件或文件夹的文件属性:
System.IO.File.SetAttributes(@"C:\汉化\汉化说明.txt",System.IO.FileAttributes.ReadOnly|System.IO.FileAttributes.Archive);
●如何判断文件或文件夹是否存在:File或Directory类都有相应的静态方法
----------------------------------------------------------------------------------------------------
0014:
如何切分文件:
●切分文件:
private void dispart(string strFileName,int intCount)
{
System.IO.FileStream myInFile = new System.IO.FileStream(@strFileName,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read);
long fileSize = Convert.ToInt64(Math.Ceiling(Convert.ToDouble(myInFile.Length)/Convert.ToDouble(intCount)));
for (int i = 0;i < intCount;i++)
{
System.IO.FileStream myOutInFile = new System.IO.FileStream((strFileName+i+".part"),System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write);
long myData = 0;
byte[] buffer = new byte[fileSize];
myData = myInFile.Read(buffer,0,Convert.ToInt32(fileSize));
if (myData > 0)
{
myOutInFile.Write(buffer,0,Convert.ToInt32(myData));
}
myOutInFile.Close();
}
myInFile.Close();
}
●组合文件:
private void compound(string strPartFileName,int intCount)
{
string strFileName = strPartFileName.Substring(0,strPartFileName.Length - 6);
System.IO.FileStream myOutInFile = new System.IO.FileStream(@strFileName,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write);
for (int i = 0;i < intCount;i++)
{
System.IO.FileStream myInFile = new System.IO.FileStream((strFileName+i+".part"),System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read);
long myData = 0;
byte[] buffer = new byte[1024];
while ((myData = myInFile.Read(buffer,0,1024)) > 0)
{
myOutInFile.Write(buffer,0,Convert.ToInt32(myData));
}
myInFile.Close();
}
myOutInFile.Close();
}
----------------------------------------------------------------------------------------------------
0015:
打开和保存文本文件:
●打开文本文件:
private void readText()
{
System.IO.StreamReader myReader = new System.IO.StreamReader(@"C:\A.txt",System.Text.Encoding.Default);
this.richTextBox1.Text = myReader.ReadToEnd();
myReader.Close();
}
●保存文本文件:
private void saveText()
{
System.IO.StreamWriter myWriter = new System.IO.StreamWriter(@"C:\A.txt",false,System.Text.Encoding.Default);
myWriter.Write(this.richTextBox1.Text);
myWriter.Close();
}
----------------------------------------------------------------------------------------------------
0016:
如何直接打印文件:PrintDocument
----------------------------------------------------------------------------------------------------
0017:
如何操作帮助文件:
●类名:Help
●打开帮助文件:System.Windows.Forms.Help.ShowHelpIndex(this,@"C:\help.chm");
----------------------------------------------------------------------------------------------------
0018:
如何操作word文件:
●主要是使用word的对象库文件MSWORD.OLB操作word文件。
●此文件路径:C:\Program Files\Microsoft Office\OFFICE11\MSWORD.OLB
●需要添加引用。
●举例:(保存为doc文件)
private void button1_Click(object sender, System.EventArgs e)
{
Microsoft.Office.Interop.Word.ApplicationClass myWord = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document myDoc;
object nothing = System.Reflection.Missing.Value;
myDoc = myWord.Documents.Add(ref nothing,ref nothing,ref nothing,ref nothing);
myDoc.Paragraphs.Last.Range.Text = this.richTextBox1.Text;
object myFileName = @"C:\A.doc";
myDoc.SaveAs(ref myFileName,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,
ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing);
myDoc.Close(ref nothing,ref nothing,ref nothing);
myWord.Quit(ref nothing,ref nothing,ref nothing);
}
----------------------------------------------------------------------------------------------------
0019:
如何播放Flash文件:
●控件名:Shockwave Flash Object
●必须先添加控件,是COM控件
●然后拖放一个控件到窗体上
●举例:(播放Flash)
axShockwaveFlash1.Movie = @"C:\A.swf";
axShockwaveFlash1.Play();
----------------------------------------------------------------------------------------------------
0020:
如何创建圆形窗体:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Drawing2D.GraphicsPath myPath = new System.Drawing.Drawing2D.GraphicsPath();
myPath.AddEllipse(20,30,this.Width - 30,this.Height - 40);
this.Region = new Region(myPath);
}
0021:
创建特别造型的窗体:
窗体的TransparencyKey属性和背景图,以及FormBorderStyle三者配合可以创建特别造型的窗体。
----------------------------------------------------------------------------------------------------
0022:
如何实现精灵提示:
●控件名:Microsoft Agent Control 2.0
●举例:
AgentObjects.IAgentCtlCharacterEx my;
axAgent1.Characters.Load("Genie",(object)@"C:\GENIE.ACS");
my = axAgent1.Characters["Genie"];
my.Show(null);
my.Speak("呵呵",null);
●注意:还需要下载相应的文件拷贝到程序目录中(Merlin不需要拷贝)。
----------------------------------------------------------------------------------------------------
0023:
如何实现程序互斥运行:
●类名:Mutex
●举例:
[STAThread]
static void Main()
{
bool ok;
System.Threading.Mutex myMutex = new System.Threading.Mutex(true,"OnlyRunOncetime",out ok);
if (ok == true)
{
Application.Run(new Form1());
myMutex.ReleaseMutex();
}
else
{
MessageBox.Show("程序已经运行!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
----------------------------------------------------------------------------------------------------
0024:
如何屏蔽各种消息:
●接口:实现接口IMessageFilter
●举例:(屏蔽左键单击事件)
public bool PreFilterMessage(ref System.Windows.Forms.Message systemMessage)//方法必须是公有的
{
if (systemMessage.Msg >= 513 && systemMessage.Msg <= 515)
{
return true;
}
return false;
}
●在窗体的加载事件中设置:
private void Form1_Load(object sender, System.EventArgs e)
{
Application.AddMessageFilter(this);
}
----------------------------------------------------------------------------------------------------
0025:
模拟键盘操作:
●类名:System.Windows.Forms.SendKeys
●举例:(向一个文本框输入字母A)
private void button1_Click(object sender, System.EventArgs e)
{
this.textBox1.Focus();
System.Windows.Forms.SendKeys.Send("A");
}
----------------------------------------------------------------------------------------------------
0026:
设置输入法:System.Windows.Forms.InputLanguage
----------------------------------------------------------------------------------------------------
0027:
在程序中启动外部程序:
●类名:System.Diagnostics.Process
●举例:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = @"C:\A.exe";
myProcess.StartInfo.Verb = "Open";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();
----------------------------------------------------------------------------------------------------
0028:
如何设置程序自动运行:
●类名:Registry和RegistryKey类
●注册表路径:HKEY_LOCAL_MACHINE\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run
●举例:
string filaName = @"C:\A.exe";
string shortFileName = @"A";
Microsoft.Win32.RegistryKey myReg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",true);
if (myReg == null)
{
myReg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
myReg.SetValue(shortFileName,filaName);
----------------------------------------------------------------------------------------------------
0029:
如何启动系统控制面板程序:
●类名:System.Runtime.InteropServices
●举例:
[DllImport("kernel32.dll")]
private static extern bool WinExec(string cmdLine,int uCmdShow);
WinExec("rundll32.exe shell32.dll,Control_RunDLL",9);//启动控制面板
WinExec("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0",9);//启动显示属性窗口\桌面
WinExec("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1",9);//启动显示属性窗口\屏幕保护
----------------------------------------------------------------------------------------------------
0030:
如何获取系统基本信息:
●类名:SystemInformation和Environment
●举例:
System.Windows.Forms.SystemInformation.ComputerName.ToString();//获取计算机名
System.Windows.Forms.SystemInformation.PrimaryMonitorMaximizedWindowSize.ToString();//获得屏幕分辨率
----------------------------------------------------------------------------------------------------
0031:
如何获取系统的所有驱动器:string[] myDrivers = System.IO.Directory.GetLogicalDrives();
----------------------------------------------------------------------------------------------------
0032:
如何禁止关闭操作系统:
●覆写WndProc方法(窗体的方法)
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0011:
systemMessage.Result = (IntPtr)0;//0是不允许关机,1是允许关机
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0033:
如何禁止屏幕保护程序:
●覆写WndProc方法
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0112:
if ((int)systemMessage.WParam == 0xF140)
{
MessageBox.Show("屏幕保护被拦截");
}
else
{
base.WndProc(ref systemMessage);
}
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0034:
禁止最大化,最小化和关闭:
●覆写WndProc方法
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0112:
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0035:
如何实现大图浏览:
●在程序界面上拖放一个Panel控件,在属性对话框中设置AutoScroll属性为true
●在Panel上拖放一个PictureBox控件,设置其SizeMode属性为AutoSize,Dock属性为None
----------------------------------------------------------------------------------------------------
0036:
以任意比例缩放显示图像:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.JPG");
Graphics g = e.Graphics;
TextureBrush myBrush = new TextureBrush(myBitmap);
float fx = (float)(0.5);
float fy = (float)(0.5);
g.ScaleTransform(fx,fy);
myBrush.ScaleTransform(fx,fy);
g.FillRectangle(myBrush,0,0,this.ClientRectangle.Width,this.ClientRectangle.Height);
}
----------------------------------------------------------------------------------------------------
0037:
实现图片按钮的方法:
private void button1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.JPG");
Graphics g = e.Graphics;
TextureBrush myBrush = new TextureBrush(myBitmap);
float fx = (float)(1);
float fy = (float)(1);
g.ScaleTransform(fx,fy);
myBrush.ScaleTransform(fx,fy);
g.FillRectangle(myBrush,0,0,this.button1.ClientRectangle.Width,this.button1.ClientRectangle.Height);
}
----------------------------------------------------------------------------------------------------
0038:
设置窗体的渐变色:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
System.Drawing.Drawing2D.LinearGradientBrush myBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
this.ClientRectangle,Color.White,Color.Blue,System.Drawing.Drawing2D.LinearGradientMode.Vertical);
g.FillRectangle(myBrush,this.ClientRectangle);
}
private void Form1_Resize(object sender, System.EventArgs e)
{
this.Refresh();
}
----------------------------------------------------------------------------------------------------
0039:
任意调整图像的大小:
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.jpg");
System.Drawing.Bitmap newBitmap = new Bitmap(myBitmap,50,50);
----------------------------------------------------------------------------------------------------
0040:
如何获取主机IP地址和主机名:
string strName = System.Net.Dns.GetHostName();
System.Net.IPHostEntry myHost = System.Net.Dns.GetHostByName(strName);
System.Net.IPAddress myIP = new System.Net.IPAddress(myHost.AddressList[0].Address);
----------------------------------------------------------------------------------------------------
0041:
如何在网页中使用广告控件:AdRotator
需要一个XML文件作文数据源:MyAdRotator.XML
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>01.jpg</ImageUrl>
<NavigateUrl>http://www.126.com<;/NavigateUrl>
<AlternateText>进入126网站</AlternateText>
<Impressions>80</Impressions>
<Keyword>126</Keyword>
<Caption>广告</Caption>
</Ad>
<Ad>
<ImageUrl>02.JPG</ImageUrl>
<NavigateUrl>http://www.163.com<;/NavigateUrl>
<AlternateText>进入163网站</AlternateText>
<Impressions>80</Impressions>
<Keyword>163</Keyword>
<Caption>广告</Caption>
</Ad>
</Advertisements>
----------------------------------------------------------------------------------------------------
0042:
Table表格控件的使用:
TableRow tr1 = new TableRow();
TableCell tc1 = new TableCell();
tc1.Text = "网易";
HyperLink hl1 = new HyperLink();
hl1.Text = "163";
hl1.NavigateUrl = "http://www.163.com";;
hl1.Target = "_Top";
TableCell tc2 = new TableCell();
tc2.Controls.Add(hl1);
tr1.Cells.Add(tc1);
tr1.Cells.Add(tc2);
this.Table1.Rows.Add(tr1);
----------------------------------------------------------------------------------------------------
0043:
日历控件的使用:Calendar
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
this.TextBox1.Text = this.Calendar1.SelectedDate.ToString();
}
----------------------------------------------------------------------------------------------------
0044:
DataGrid的按钮单击处理:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Out")
{
string str = "<script>alert(\'"+this.GridView1.Rows[1].Cells[1].Text+"\')</script>";
Response.Write(str);
}
}
----------------------------------------------------------------------------------------------------
0045:
RadioButtonList控件的使用:
●将RadioButtonList控件的AutoPostBack设置为true
●CS部分:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "<script>alert(\'" + this.RadioButtonList1.SelectedItem.Text + "\')</script>";
Response.Write(str);
}
----------------------------------------------------------------------------------------------------
0046:
获得客户端的浏览器信息:
protected void Page_Load(object sender, EventArgs e)
{
HttpBrowserCapabilities hrc = this.Request.Browser;
Response.Write(hrc.Cookies);
Response.Write("<br>");
Response.Write(hrc.JavaScript);
}
----------------------------------------------------------------------------------------------------
0047:
浏览显示图象:
●添加pic.aspx窗体,且有下面的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
string str = (string)Session["filename"];
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(str);
System.Drawing.TextureBrush tb = new System.Drawing.TextureBrush(bm);
bm = new System.Drawing.Bitmap(bm.Width, bm.Height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
g.Clear(System.Drawing.Color.White);
g.FillRectangle(tb, 0, 0, bm.Width, bm.Height);
Response.ContentType = "image/gif";
bm.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
}
}
●在Default.aspx中的<form></form>间添加<iframe><iframe>:
<iframe id="IFRAME1" runat="server" style="width: 371px; height: 371px">
</iframe>
●Default.aspx中单击按钮:
protected void Button1_Click(object sender, EventArgs e)
{
Session["filename"] = this.FileUpload1.PostedFile.FileName;
this.IFRAME1.Attributes["src"] = "Pic.aspx";
}
如何使用错误提醒控件:
●控件名:ErrorProvider
●设置错误提醒:(当鼠标离开输入文本框时,如果输入的字符串长度小于5则提示)
private void textBox1_MouseLeave(object sender, System.EventArgs e)
{
if(this.textBox1.Text.Trim().Length <= 5)
{
errorProvider1.SetError(this.textBox1,"必须输入5位以上长度的字符串");
}
}
●取消错误提醒:(当鼠标进入输入文本框区域的时候发生)
private void textBox1_MouseEnter(object sender, System.EventArgs e)
{
errorProvider1.Dispose();
}
----------------------------------------------------------------------------------------------------
0002:
信息提示框的使用:
●控件名:MessageBox
●对用户选择判断:
DialogResult temp = MessageBox.Show(this,"用户输入错误,是否从新输入?","提示",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
switch(temp)
{
case DialogResult.Retry:
//
break;
case DialogResult.Cancel:
//
break;
}
----------------------------------------------------------------------------------------------------
0003:
如何使用信息提示控件:
●控件名:ToolTip
●提示信息:(多行提示信息的情况,@)
this.toolTip1.SetToolTip(this.textBox1,@"1,请输入数字
2,请输入数字
3,请输入数字
4,请输入数字");
●提示信息:(多行提示信息的情况,无@)
this.toolTip1.SetToolTip(this.textBox1,"1,请输入数字\n2,请输入数字\n3,请输入数字\n4,请输入数字");
----------------------------------------------------------------------------------------------------
0004:
如何使用菜单控件:
●控件名:MainMenu
●横线:输入一个"-",就会编程横线
●快捷键:在菜单名称中,"&"符号后面的字母代表了菜单的快捷键(Ctrl+字符)
●切换显示菜单前面被选中的小对勾:
private void menuItem2_Click(object sender, System.EventArgs e)
{
this.menuItem2.Checked = !this.menuItem2.Checked;
}
●如果设置menuItem2的RadioChecked属性为true,则会显示一个小黑点,而不是对勾,然后通过算法实现互
斥选择
----------------------------------------------------------------------------------------------------
0005:
如何使用工具栏控件:
●控件名:ToolBar
●添加按钮:单击Buttons属性
●单击的实现:
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
ToolBarButton temp = e.Button;
if(temp == this.toolBarButton1)
{
MessageBox.Show("1");
}
else if(temp == this.toolBarButton2)
{
MessageBox.Show("2");
}
else if(temp == this.toolBarButton3)
{
MessageBox.Show("3");
}
}
●注意:不能使用switch来进行选择判断
●ToolBar上的图标可以使用ImageList控件来设置
●在Buttons属性中添加按钮时,按钮还可以添加下拉菜单,DropDownMenu。添加的是ContextMenu控件,并且
设置其Style属性为DropDownButton。不要添加主菜单的DropDownMenu属性。
----------------------------------------------------------------------------------------------------
0006:
打开文件控件:
●控件名:OpenFileDialog
●举例:
//this.openFileDialog1.Filter = "文本文件(*.txt)|*.txt|文本文件(*.doc)|*.doc";
//this.openFileDialog1.Filter = "文本文件|*.txt;*.doc";
//this.openFileDialog1.Filter = "Jpeg|*.jpg;*jpeg|Tif|*.tif;*tiff|All files|*.*";
this.openFileDialog1.ShowDialog();
String str = this.openFileDialog1.FileName;
----------------------------------------------------------------------------------------------------
0007:
如何使用状态栏控件:
●控件名:StatusBar
●首先要设置StatusBar的ShowPanels的属性为真,然后设置其Panels属性
●举例:(显示鼠标的坐标)
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.statusBarPanel1.Text = Cursor.Position.X + " " + Cursor.Position.Y;
}
----------------------------------------------------------------------------------------------------
0008:
e.KeyCode:可以用于判断文本框等输入的内容是字符还是数字
private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
label1.Text = e.KeyCode.ToString();
}
----------------------------------------------------------------------------------------------------
0009:
如何使用托盘控件:
●控件名:NotifyIcon
●NotifyIcon可以设置右键菜单,右键菜单是ContextMenu控件
----------------------------------------------------------------------------------------------------
0010:
如何使用树状视图控件:
●控件名:TreeView
●举例:
TreeNode newNode1 = new TreeNode("根节点1",0,0);
TreeNode newNode2 = new TreeNode("根节点2",0,0);
TreeNode newNode3 = new TreeNode("根节点3",0,0);
TreeNode newNode31 = new TreeNode("子节点31",0,0);
TreeNode newNode32 = new TreeNode("子节点32",0,0);
TreeNode newNode33 = new TreeNode("子节点33",0,0);
this.treeView1.Nodes.Add(newNode1);
this.treeView1.Nodes.Add(newNode2);
this.treeView1.Nodes.Add(newNode3);
newNode3.Nodes.Add(newNode31);
newNode3.Nodes.Add(newNode32);
newNode3.Nodes.Add(newNode33);
newNode3.Expand();//展开子节点
this.treeView1.Select();
●选择某一个节点:
this.treeView1.SelectedNode = this.treeView1.Nodes[1];
this.treeView1.Select();
----------------------------------------------------------------------------------------------------
0011:
如何使用列表视图控件:
●控件名:ListView
●注意:应该把View属性改为Details
●举例:
private void Form1_Load(object sender, System.EventArgs e)
{
int i = this.listView1.Items.Count;
string[] s1 = {"张三","28岁","男"};
this.listView1.Items.Insert(i,new ListViewItem(s1));
string[] s2 = {"李四","22岁","女"};
this.listView1.Items.Insert(i,new ListViewItem(s2));
string[] s3 = {"马六","26岁","男"};
this.listView1.Items.Insert(i,new ListViewItem(s3));
}
----------------------------------------------------------------------------------------------------
0012:
如何使用窗体分隔控件:
●控件名:Splitter
●使用顺序:
(1)拖放一个RichTextBox控件
(2)设置其Dock为Bottom
(3)拖放一个Splitter控件
(4)设置其Dock为Bottom
●注意:如果还有其它控件需要拖动,需要再增加Splitter控件
----------------------------------------------------------------------------------------------------
0013:
如何获取程序文件信息:
●获取当前程序可执行文件的路径信息:Application.ExecutablePath.ToString()
●获取当前程序可执行文件的文件夹路径信息:Application.StartupPath.ToString()
●获取任意文件的信息:
System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath);//输入fileName
MessageBox.Show(info.FileName);
●返回文件根目录信息:string str = System.IO.Directory.GetDirectoryRoot(@"C:\汉化\汉化说明.txt");
●返回文件的父目录信息:System.IO.DirectoryInfo info = System.IO.Directory.GetParent(@"C:\汉化\汉化说明.txt");
●返回当前程序所在的文件夹:string str = System.IO.Directory.GetCurrentDirectory();
●获取指定文件夹下的所有信息:string[] str = System.IO.Directory.GetFiles(@"C:\汉化");
●如何使用ListBox控件显示信息:
string[] str = System.IO.Directory.GetFiles(@"C:\汉化");
this.listBox1.Items.AddRange(str);
●如何获取指定文件的文件属性:System.IO.FileAttributes fa = System.IO.File.GetAttributes(@"C:\汉化\汉化说明.txt");
●设置指定文件或文件夹的文件属性:
System.IO.File.SetAttributes(@"C:\汉化\汉化说明.txt",System.IO.FileAttributes.ReadOnly|System.IO.FileAttributes.Archive);
●如何判断文件或文件夹是否存在:File或Directory类都有相应的静态方法
----------------------------------------------------------------------------------------------------
0014:
如何切分文件:
●切分文件:
private void dispart(string strFileName,int intCount)
{
System.IO.FileStream myInFile = new System.IO.FileStream(@strFileName,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read);
long fileSize = Convert.ToInt64(Math.Ceiling(Convert.ToDouble(myInFile.Length)/Convert.ToDouble(intCount)));
for (int i = 0;i < intCount;i++)
{
System.IO.FileStream myOutInFile = new System.IO.FileStream((strFileName+i+".part"),System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write);
long myData = 0;
byte[] buffer = new byte[fileSize];
myData = myInFile.Read(buffer,0,Convert.ToInt32(fileSize));
if (myData > 0)
{
myOutInFile.Write(buffer,0,Convert.ToInt32(myData));
}
myOutInFile.Close();
}
myInFile.Close();
}
●组合文件:
private void compound(string strPartFileName,int intCount)
{
string strFileName = strPartFileName.Substring(0,strPartFileName.Length - 6);
System.IO.FileStream myOutInFile = new System.IO.FileStream(@strFileName,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write);
for (int i = 0;i < intCount;i++)
{
System.IO.FileStream myInFile = new System.IO.FileStream((strFileName+i+".part"),System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read);
long myData = 0;
byte[] buffer = new byte[1024];
while ((myData = myInFile.Read(buffer,0,1024)) > 0)
{
myOutInFile.Write(buffer,0,Convert.ToInt32(myData));
}
myInFile.Close();
}
myOutInFile.Close();
}
----------------------------------------------------------------------------------------------------
0015:
打开和保存文本文件:
●打开文本文件:
private void readText()
{
System.IO.StreamReader myReader = new System.IO.StreamReader(@"C:\A.txt",System.Text.Encoding.Default);
this.richTextBox1.Text = myReader.ReadToEnd();
myReader.Close();
}
●保存文本文件:
private void saveText()
{
System.IO.StreamWriter myWriter = new System.IO.StreamWriter(@"C:\A.txt",false,System.Text.Encoding.Default);
myWriter.Write(this.richTextBox1.Text);
myWriter.Close();
}
----------------------------------------------------------------------------------------------------
0016:
如何直接打印文件:PrintDocument
----------------------------------------------------------------------------------------------------
0017:
如何操作帮助文件:
●类名:Help
●打开帮助文件:System.Windows.Forms.Help.ShowHelpIndex(this,@"C:\help.chm");
----------------------------------------------------------------------------------------------------
0018:
如何操作word文件:
●主要是使用word的对象库文件MSWORD.OLB操作word文件。
●此文件路径:C:\Program Files\Microsoft Office\OFFICE11\MSWORD.OLB
●需要添加引用。
●举例:(保存为doc文件)
private void button1_Click(object sender, System.EventArgs e)
{
Microsoft.Office.Interop.Word.ApplicationClass myWord = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document myDoc;
object nothing = System.Reflection.Missing.Value;
myDoc = myWord.Documents.Add(ref nothing,ref nothing,ref nothing,ref nothing);
myDoc.Paragraphs.Last.Range.Text = this.richTextBox1.Text;
object myFileName = @"C:\A.doc";
myDoc.SaveAs(ref myFileName,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,
ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing);
myDoc.Close(ref nothing,ref nothing,ref nothing);
myWord.Quit(ref nothing,ref nothing,ref nothing);
}
----------------------------------------------------------------------------------------------------
0019:
如何播放Flash文件:
●控件名:Shockwave Flash Object
●必须先添加控件,是COM控件
●然后拖放一个控件到窗体上
●举例:(播放Flash)
axShockwaveFlash1.Movie = @"C:\A.swf";
axShockwaveFlash1.Play();
----------------------------------------------------------------------------------------------------
0020:
如何创建圆形窗体:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Drawing2D.GraphicsPath myPath = new System.Drawing.Drawing2D.GraphicsPath();
myPath.AddEllipse(20,30,this.Width - 30,this.Height - 40);
this.Region = new Region(myPath);
}
0021:
创建特别造型的窗体:
窗体的TransparencyKey属性和背景图,以及FormBorderStyle三者配合可以创建特别造型的窗体。
----------------------------------------------------------------------------------------------------
0022:
如何实现精灵提示:
●控件名:Microsoft Agent Control 2.0
●举例:
AgentObjects.IAgentCtlCharacterEx my;
axAgent1.Characters.Load("Genie",(object)@"C:\GENIE.ACS");
my = axAgent1.Characters["Genie"];
my.Show(null);
my.Speak("呵呵",null);
●注意:还需要下载相应的文件拷贝到程序目录中(Merlin不需要拷贝)。
----------------------------------------------------------------------------------------------------
0023:
如何实现程序互斥运行:
●类名:Mutex
●举例:
[STAThread]
static void Main()
{
bool ok;
System.Threading.Mutex myMutex = new System.Threading.Mutex(true,"OnlyRunOncetime",out ok);
if (ok == true)
{
Application.Run(new Form1());
myMutex.ReleaseMutex();
}
else
{
MessageBox.Show("程序已经运行!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
----------------------------------------------------------------------------------------------------
0024:
如何屏蔽各种消息:
●接口:实现接口IMessageFilter
●举例:(屏蔽左键单击事件)
public bool PreFilterMessage(ref System.Windows.Forms.Message systemMessage)//方法必须是公有的
{
if (systemMessage.Msg >= 513 && systemMessage.Msg <= 515)
{
return true;
}
return false;
}
●在窗体的加载事件中设置:
private void Form1_Load(object sender, System.EventArgs e)
{
Application.AddMessageFilter(this);
}
----------------------------------------------------------------------------------------------------
0025:
模拟键盘操作:
●类名:System.Windows.Forms.SendKeys
●举例:(向一个文本框输入字母A)
private void button1_Click(object sender, System.EventArgs e)
{
this.textBox1.Focus();
System.Windows.Forms.SendKeys.Send("A");
}
----------------------------------------------------------------------------------------------------
0026:
设置输入法:System.Windows.Forms.InputLanguage
----------------------------------------------------------------------------------------------------
0027:
在程序中启动外部程序:
●类名:System.Diagnostics.Process
●举例:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = @"C:\A.exe";
myProcess.StartInfo.Verb = "Open";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();
----------------------------------------------------------------------------------------------------
0028:
如何设置程序自动运行:
●类名:Registry和RegistryKey类
●注册表路径:HKEY_LOCAL_MACHINE\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run
●举例:
string filaName = @"C:\A.exe";
string shortFileName = @"A";
Microsoft.Win32.RegistryKey myReg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",true);
if (myReg == null)
{
myReg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
myReg.SetValue(shortFileName,filaName);
----------------------------------------------------------------------------------------------------
0029:
如何启动系统控制面板程序:
●类名:System.Runtime.InteropServices
●举例:
[DllImport("kernel32.dll")]
private static extern bool WinExec(string cmdLine,int uCmdShow);
WinExec("rundll32.exe shell32.dll,Control_RunDLL",9);//启动控制面板
WinExec("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0",9);//启动显示属性窗口\桌面
WinExec("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1",9);//启动显示属性窗口\屏幕保护
----------------------------------------------------------------------------------------------------
0030:
如何获取系统基本信息:
●类名:SystemInformation和Environment
●举例:
System.Windows.Forms.SystemInformation.ComputerName.ToString();//获取计算机名
System.Windows.Forms.SystemInformation.PrimaryMonitorMaximizedWindowSize.ToString();//获得屏幕分辨率
----------------------------------------------------------------------------------------------------
0031:
如何获取系统的所有驱动器:string[] myDrivers = System.IO.Directory.GetLogicalDrives();
----------------------------------------------------------------------------------------------------
0032:
如何禁止关闭操作系统:
●覆写WndProc方法(窗体的方法)
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0011:
systemMessage.Result = (IntPtr)0;//0是不允许关机,1是允许关机
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0033:
如何禁止屏幕保护程序:
●覆写WndProc方法
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0112:
if ((int)systemMessage.WParam == 0xF140)
{
MessageBox.Show("屏幕保护被拦截");
}
else
{
base.WndProc(ref systemMessage);
}
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0034:
禁止最大化,最小化和关闭:
●覆写WndProc方法
●举例:
protected override void WndProc(ref Message systemMessage)
{
switch(systemMessage.Msg)
{
case 0x0112:
break;
default:
base.WndProc(ref systemMessage);
break;
}
}
----------------------------------------------------------------------------------------------------
0035:
如何实现大图浏览:
●在程序界面上拖放一个Panel控件,在属性对话框中设置AutoScroll属性为true
●在Panel上拖放一个PictureBox控件,设置其SizeMode属性为AutoSize,Dock属性为None
----------------------------------------------------------------------------------------------------
0036:
以任意比例缩放显示图像:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.JPG");
Graphics g = e.Graphics;
TextureBrush myBrush = new TextureBrush(myBitmap);
float fx = (float)(0.5);
float fy = (float)(0.5);
g.ScaleTransform(fx,fy);
myBrush.ScaleTransform(fx,fy);
g.FillRectangle(myBrush,0,0,this.ClientRectangle.Width,this.ClientRectangle.Height);
}
----------------------------------------------------------------------------------------------------
0037:
实现图片按钮的方法:
private void button1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.JPG");
Graphics g = e.Graphics;
TextureBrush myBrush = new TextureBrush(myBitmap);
float fx = (float)(1);
float fy = (float)(1);
g.ScaleTransform(fx,fy);
myBrush.ScaleTransform(fx,fy);
g.FillRectangle(myBrush,0,0,this.button1.ClientRectangle.Width,this.button1.ClientRectangle.Height);
}
----------------------------------------------------------------------------------------------------
0038:
设置窗体的渐变色:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
System.Drawing.Drawing2D.LinearGradientBrush myBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
this.ClientRectangle,Color.White,Color.Blue,System.Drawing.Drawing2D.LinearGradientMode.Vertical);
g.FillRectangle(myBrush,this.ClientRectangle);
}
private void Form1_Resize(object sender, System.EventArgs e)
{
this.Refresh();
}
----------------------------------------------------------------------------------------------------
0039:
任意调整图像的大小:
System.Drawing.Bitmap myBitmap = new Bitmap(@"C:\A.jpg");
System.Drawing.Bitmap newBitmap = new Bitmap(myBitmap,50,50);
----------------------------------------------------------------------------------------------------
0040:
如何获取主机IP地址和主机名:
string strName = System.Net.Dns.GetHostName();
System.Net.IPHostEntry myHost = System.Net.Dns.GetHostByName(strName);
System.Net.IPAddress myIP = new System.Net.IPAddress(myHost.AddressList[0].Address);
----------------------------------------------------------------------------------------------------
0041:
如何在网页中使用广告控件:AdRotator
需要一个XML文件作文数据源:MyAdRotator.XML
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>01.jpg</ImageUrl>
<NavigateUrl>http://www.126.com<;/NavigateUrl>
<AlternateText>进入126网站</AlternateText>
<Impressions>80</Impressions>
<Keyword>126</Keyword>
<Caption>广告</Caption>
</Ad>
<Ad>
<ImageUrl>02.JPG</ImageUrl>
<NavigateUrl>http://www.163.com<;/NavigateUrl>
<AlternateText>进入163网站</AlternateText>
<Impressions>80</Impressions>
<Keyword>163</Keyword>
<Caption>广告</Caption>
</Ad>
</Advertisements>
----------------------------------------------------------------------------------------------------
0042:
Table表格控件的使用:
TableRow tr1 = new TableRow();
TableCell tc1 = new TableCell();
tc1.Text = "网易";
HyperLink hl1 = new HyperLink();
hl1.Text = "163";
hl1.NavigateUrl = "http://www.163.com";;
hl1.Target = "_Top";
TableCell tc2 = new TableCell();
tc2.Controls.Add(hl1);
tr1.Cells.Add(tc1);
tr1.Cells.Add(tc2);
this.Table1.Rows.Add(tr1);
----------------------------------------------------------------------------------------------------
0043:
日历控件的使用:Calendar
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
this.TextBox1.Text = this.Calendar1.SelectedDate.ToString();
}
----------------------------------------------------------------------------------------------------
0044:
DataGrid的按钮单击处理:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Out")
{
string str = "<script>alert(\'"+this.GridView1.Rows[1].Cells[1].Text+"\')</script>";
Response.Write(str);
}
}
----------------------------------------------------------------------------------------------------
0045:
RadioButtonList控件的使用:
●将RadioButtonList控件的AutoPostBack设置为true
●CS部分:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "<script>alert(\'" + this.RadioButtonList1.SelectedItem.Text + "\')</script>";
Response.Write(str);
}
----------------------------------------------------------------------------------------------------
0046:
获得客户端的浏览器信息:
protected void Page_Load(object sender, EventArgs e)
{
HttpBrowserCapabilities hrc = this.Request.Browser;
Response.Write(hrc.Cookies);
Response.Write("<br>");
Response.Write(hrc.JavaScript);
}
----------------------------------------------------------------------------------------------------
0047:
浏览显示图象:
●添加pic.aspx窗体,且有下面的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
string str = (string)Session["filename"];
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(str);
System.Drawing.TextureBrush tb = new System.Drawing.TextureBrush(bm);
bm = new System.Drawing.Bitmap(bm.Width, bm.Height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
g.Clear(System.Drawing.Color.White);
g.FillRectangle(tb, 0, 0, bm.Width, bm.Height);
Response.ContentType = "image/gif";
bm.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
}
}
●在Default.aspx中的<form></form>间添加<iframe><iframe>:
<iframe id="IFRAME1" runat="server" style="width: 371px; height: 371px">
</iframe>
●Default.aspx中单击按钮:
protected void Button1_Click(object sender, EventArgs e)
{
Session["filename"] = this.FileUpload1.PostedFile.FileName;
this.IFRAME1.Attributes["src"] = "Pic.aspx";
}