Csharp日常笔记

时间:2023-03-09 03:50:48
Csharp日常笔记

1.

Csharp日常笔记

1.退出程序
                  this.Close();             //方法退关闭当前窗口。

Application.Exit();       //方法退出整个应用程序。  (无法退出单独开启的线程)

Application.ExitThread(); //释放所有线程   

Environment.Exit(0);      //可以退出单独开启的线程

2.从本窗口Form1点击按钮产生新窗口Form2
      Form2 f2 = new Form2();
      F2.Show();

3.得到现在时间并显示在label1上
      Label1.Text=DateTime.Now.Hour+":"+DateTime.Now.Minute+":"+DateTime.Now.Second

4.产生0到100的随机数
      int m=0;
      Random r = new Random();
      m=r.Next(0,100);

5.改变窗口大小
      //把窗口的高变为100像素,宽不变
      this.Size=new Size(this.Size.Width,100);
      //把窗口的宽变为100像素,高不变
      this.Size=new Size(100,this.Size.Height);
      //把窗口的高和宽都变为100像素
      this.Size=new Size(100,100);

6.改变控件的位置
      //改变按钮button1的位置到坐标为(100,100)处
      button1.Location=new Point(100,100);
      //改变文字label1的位置到坐标为(100,100)处
      label1.Location=new Point(100,100);

7. 指定位置创建一个文件夹(创建D盘Folder文件夹为例)
      #需要导入Using System.IO
      Directory.CreateDirectory(@"D:\Folder");

8. 指定位置创建一个文件(以创建D盘test.txt为例)
      #需要导入Using System.IO
      FileStream fs= File.Create(@"D:\test.txt");

FileSystem.FileOpen(1,"D:\test.txt",Binary)
      FileSystem.FileClose(1)

9. 复制一个文件到另一位置(以test.txt文件为例)
      #需要导入Using System.IO
      #其中有true表示test2.txt已经存在的话就覆盖
      File.Copy(@"D:\test.txt",@"D:\temp\test2.txt",true);

10. 移动文件(以test.txt为例)
      #需要导入Using System.IO
      File.Move(@"d:\test.txt",@"d:\temp\test.txt");

and

My.Computer.FileSystem.CopyFile("d:\test.txt","d:\temp\test.txt")

11.检测当前操作系统信息显示到Label1上
      string os = System.Environment.OSVerion.ToString();
      Label1.Text="检测到您使用的操作系统是:"+os;

Label1.Text="检测到您使用的操作系统是:"+My.Computer.Info.OSVersion

12.启动进程打开网页或者某个程序(打开百度首页为例)
      System.Diagnostics.Process.Start(@"http://www.baidu.com/");

13.判断文件是否存在(以C盘test.txt为例)
      #需要引入 using System.IO;
      File.Exists(@"C:\test.txt");
      返回true或者false;
      //判断可用
      if (File.Exists(@"C:\test.txt"))
      {
      }

14.弹出对话框
      //仅提示内容
      MessageBox.Show("提示内容");
      //标题和内容,以及图标
      MessageBox.Show("提示内容","标题",MessageBoxButtons.Yes,MessageBoxIcon.Information);

15.判断用户是否点击了弹出的对话框中的确定/Ok/Yes,将判断结果显示在label1上
      DialogResult dr = MessageBox.Show("提示内容","标题",MessageBoxButtons.Yes,MessageBoxIcon.Information);
      if(dr==DialogResult.Yes)
      {
      label1.Text="你点击了对话框中的[Yes]";
      }

16.为泛型赋值
      List<Int32> lst = new List<Int32> { };
      for (Int32 mm = 0; mm <= 100; mm++)
      { 
      lst.Add(mm);
      }

17.

关机 System.Diagnostics.Process.Start("shutdown", "-s -t 0");
      注销 System.Diagnostics.Process.Start("shutdown", "-l ");
      重启 System.Diagnostics.Process.Start("shutdown", "-r -t 0");

18.某月有几天 DateTime.DaysInMonth(2012,1)

19.按行写入数据到文本(以C盘test.txt为例)
      需要导入System.IO;
      FileStream fs = new FileStream(@"C:\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 
      StreamWriter sw = new StreamWriter(fs); 
      sw.WriteLine( "第一行\r\n第二行\r\n第三行" ); 
      sw.Flush(); 
      sw.Close(); 
      fs.Close();

20..通过静态类跨窗体传递数据(以Form1通过dataPass.cs静态类传递数据到Form2为例)
      //构造静态类
      public static class dataPass
      { 
      public static String _isData;
      public static String isData 
      { 
      get { return _isData; } 
      set { _isData = value; } 
      } 
      }
      //在Form1中的一个按钮Button1上点击转到Form2
      private void Button1_Click_1(object sender, EventArgs e)
      { 
      //把Button1上的文字存入静态类
      dataPass._isData=Button1.Text;
      Form2 f2 = new Form2();
      f2.Show();
      }
      //在Form2加载的时候把数据传递到Form2的标题上显示
      private void Form2_Load(object sender, EventArgs e) 
      {
      this.Text=dataPass._isData;
      }

form1:  private void button1_Click(object sender, EventArgs e)        {            string aa = "aa";            Form2 form2 = new Form2(aa);           
form2.ShowDialog();        }form2:   private string text;         public Form2(string str)        {            InitializeComponent();            text = str;        }         private void Form2_Load(object sender, EventArgs e)        {            label1.Text
= text;

}

21. 获得某个文件夹中的所有文件名(以获得Images文件夹中的所有图片文件名为例)
      #需要引用using System.IO; 
      String Path="Images";
      List<string> files = null;
      string getFilesFilter = "*.jpg;*.jpeg;*.jpe;*.gif;*.bmp;*.png;";
      string[] arrFilter = getFilesFilter.Split(';');
      if (!string.IsNullOrEmpty(Path))
      {
      files = new List<string>();
      try
      {
      DirectoryInfo di = new DirectoryInfo("Images");
      for (int i = 0; i < arrFilter.Length; i++)
      {
      if (di.Exists)
      {
      foreach (FileInfo fileInfo in di.GetFiles(arrFilter[i]))
      {
      files.Add(fileInfo.FullName);
      if (files.Count > 50)
      break;
      }
      }
      }
      }
      catch (IOException) { }
      catch (ArgumentException) { }
      catch (SecurityException) { }
      }

22. 剪切板操作(以textBox1中的文本为例)
      //放入剪贴板
      Clipboard.SetText(textBox1.Text); 
      //从剪切板取出文本
      textBox1.Text = Clipboard.GetText();

23.获得系统某些特殊目录的路径
      //桌面
      string desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
      //文档
      string documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
      //program Files
      string desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);

24. 创建程序的桌面快捷方式(以C盘llyn23.exe为例)
      #需要添加引用 (com->Windows Script Host Object Model)
      #需要引入using IWshRuntimeLibrary;
      //得到桌面路径
      string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); 
      IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();
      IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(DesktopPath + "\\llyn23快捷方式.lnk"); 
      shortcut.TargetPath = @"C:\llyn23.exe"; 
      shortcut.Arguments = ""; 
      shortcut.Description = "llyn23快捷方式"; 
      shortcut.WorkingDirectory = @"C:\";
      //设置图标
      shortcut.IconLocation = @"C:\llyn23.exe,0"; 
      //设置热键
      shortcut.Hotkey = "CTRL+SHIFT+Z"; 
      shortcut.WindowStyle = 1; 
      shortcut.Save();

25 获取屏幕宽度:

this.Width = System.Windows.Forms.Screen.GetBounds(this).Width;

//获得当前屏幕的分辨率
       Screen scr =Screen.PrimaryScreen;
       Rectangle rc =scr.Bounds;
       intiWidth =rc.Width;

intiHeight =rc.Height;

26.程序当前目录下文件:("..\\..\\banana.ico")

27.以方法调用方式计算圆面积(点击button1后计算,以半径为10.0为例)
      private void btn_enter_Click(object sender, EventArgs e)
      {
      AreaCount(10.0);
      }
      public Double AreaCount(Double moRadius)
      {
      //可以直接使用Math.PI,即圆周率3.14159265358979323846 
      return Math.PI * moRadius * moRadius ;
      }

28用静态类的方法移动无边框窗口(窗口以Form1为例,静态类以dataPass.cs为例)
      //创建静态类
      public static class dataPass
      { 
      public static Int32 _mouseX; 
      public static Int32 _mouseY;
      public static Int32 mouseX 
      { 
      get { return _mouseX; } 
      set { _mouseX = value; } 
      }
      public static Int32 mouseY 
      { 
      get { return _mouseY; } 
      set { _mouseY = value; } 
      }
      }
      //鼠标按下事件中记录鼠标初始坐标
      private void Form1_MouseDown(object sender, MouseEventArgs e) 
      { 
      dataPass._mouseX = e.X; 
      dataPass._mouseY = e.Y; 
      }
      //鼠标移动事件中改变Form1的位置
      private void Form1_MouseMove(object sender, MouseEventArgs e) 
      { 
      //先判断鼠标左键是否已按下,按下了才移动Form1 
      if (e.Button == MouseButtons.Left) 
      { 
      //新位置为原位置+现在鼠标坐标-初始鼠标坐标
      this.Location = new Point(this.Location.X + e.X - dataPass._mouseX, this.Location.Y + e.Y - dataPass._mouseY); 
      } 
      }

29. 以创建一个坐标点对象,计算偏移量的方式来移动无边框窗体
      private Point moePoint;
      private void Form1_MouseDown(object sender, MouseEventArgs e) 
      { 
      moePoint= new Point(-e.X,-e.Y);
      }
      private void Form1_MouseMove(object sender, MouseEventArgs e) 
      { 
      if (e.Button == MouseButtons.Left) 
      { 
      Point moePosition = Control.MousePotision;
      //偏移
      moePosition.Offset(moePoint.X,moePoint.Y);
      this.DesktopLocation=moePosition;
      } 
      }

30. 判断列表选中项来改变窗体背景颜色(以comboBox1,Form1为例)
      //创建颜色数组
      public System.Drawing.Color[] arrColor = { Color.Red,Color.Green,Color.Blue,Color.Purple,Color.Pink,Color.Yellow};
      //注意列表项数不要超过颜色数组中元素个数
      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
      {
      Form1.BackColor=arrColor[comboBox1.SelectedIndex];
      }

31. 变换背景颜色4种方式(以改变Form1的背景颜色为例)
      //使用既有颜色
      Form1.BackColor=Color.Red;
      //使用透明度+既有颜色方式,透明度的值从0到255,255为完全不透明
      Form1.BackColor=Color.FromArgb(255,Color.Red);
      //自定义颜色,不含透明,3个参数分别是红色,绿色,蓝色,值从0~255
      Form1.BackColor=Color.FromArgb(255,0,128); 
      //自定义颜色,含透明,4个参数分别是透明度,红色,绿色,蓝色,值从0~255 
      Form1.BackColor=Color.FromArgb(192,255,0,128);

32. 扑克牌随机发牌(4人为例)
      static void Main(string[] args)
      {
      int i, j, temp;
      Random Rnd = new Random();
      int k;
      int [] Card = new int[52];
      int [,] Player = new int[4, 3]; for (i = 0; i < 4; i++) //52张牌初始化
      for (j = 0; j < 13; j++)
      Card[i * 13 + j] = (i + 1) * 100 + j + i;
      Console.Write("How many times for card:");
      string s = Console.ReadLine();
      int times = Convert.ToInt32(s);
      for (j=1;j<=times;j++)
      for (i = 0; i < 52; i++)
      {
      k = Rnd.Next(51 - i + 1) + i;//产生i到52的之间的随机数
      temp = Card[i];
      Card[i] = Card[k];
      Card[k] = temp;
      }
      k = 0;
      for (j = 0; j < 13; j++)//52张牌分给4个玩家
      for (i = 0; i < 4; i++)
      Player[i, j] = Card[k++];
      for(i=0;i<4;i++)//显示4个玩家的牌
      {
      Console.WriteLine ("玩家{0}的牌:",i+1);
      for(j=0;j<13;j++)
      {
      k =(int)Player[i,j]/100;//分离出牌的种类
      switch (k)
      {
      case 1: //红桃
      s=Convert.ToString('\x0003');
      break;
      case 2: //方块
      s=Convert.ToString('\x0004');
      break;
      case 3: //梅花
      s=Convert.ToString('\x0005');
      break;
      case 4: //黑桃
      s=Convert.ToString('\x0006');
      break;
      }
      k=Player[i,j]%100;
      switch(k)
      {
      case 1:
      s =s+"A";
      break;
      case 11:
      s =s+"J";
      break;
      case 12:
      s =s+"Q";
      break;
      case 13:
      s =s+"K";
      break;
      default:
      s=s+Convert .ToString(k);
      break;
      }
      Console.Write (s);
      if (j<12)
      Console.Write (",");
      else 
      Console.Write(" "); 
      }
      } Console.Read();
      }

33. 创建一个渐变色背景按钮控件
      #创建控件请点击"新建"->"项目"->"Windows窗体控件库"->编码->引用
      using System;using System.Collections.Generic;
      using System.ComponentModel;
      using System.Drawing;
      using System.Data;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;
      namespace moeButton
      { 
      //此处新建好项目后修修改成如下以继承Button
      public partial class moeButton : System.Windows.Forms.Button 
      { 
      private Color _moeColor1 = Color.Magenta; 
      private Color _moeColor2 = Color.Cyan; 
      private int _moTransparent1 = 128; 
      private int _moTransparent2 = 128;
      public Color moeColor1 
      { 
      get { return _moeColor1; } 
      set { _moeColor1 = value; } 
      }
      public Color moeColor2 
      { 
      get { return _moeColor2; } 
      set { _moeColor2 = value; } 
      }
      public int moTransparent1 
      { 
      get { return _moTransparent1; } 
      set { _moTransparent1 = value; } 
      }
      public int moTransparent2 
      { 
      get { return _moTransparent2; } 
      set { _moTransparent2 = value; } 
      }
      public moeButton() 
      { 
      }
      protected override void OnPaint(PaintEventArgs pevent) 
      { 
      base.OnPaint(pevent); 
      Color c1 = Color.FromArgb(_moTransparent1,_moeColor1); 
      Color c2 = Color.FromArgb(_moTransparent2, _moeColor2); 
      Brush br = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle,c1,c2,10); 
      pevent.Graphics.FillRectangle(br,ClientRectangle); 
      br.Dispose(); 
      } 
      }
      }

34.获取剪切板的图片
      IDataObject data = Clipboard.GetDataObject();//从剪贴板中获取数据
      if(data.GetDataPresent(typeof(Bitmap)))//判断是否是图片数据
      {
      Bitmap map = (Bitmap) data.GetData(typeof(Bitmap));//将图片数据存到位图中
      this.pictureBox1.Image = map;//显示
      map.Save(@"C:\a.bmp");//保存图片

35. 使用SQL Server身份验证
      #moeData为数据库名,Prism为电脑名称,SQLExpress为使用的SQL Server版本
      //不要在程序中硬编码用户名和密码
      //使用Linq to Sql 来管理数据库就不需要手写这些代码
      String userName = "mo";
      String userPass = "1234";
      String connStr= String.Format("User ID ={0};Password ={1};Initial Catalog = moeData;"+"Data Source=Prism\\SQLExpress",userName,userPass);
      Sqlconnection moConnection=newSqlConnection();
      moConnection.ConnectionString = connStr;

36. 保存文件对话框与写入数据的综合应用及线程模拟假死
      #Using System.IO;
      #Using System.Theading;
      //SaveDialog.ShowDialog().Value为true 或 flase,必须先点SaveDialog中的确定或取消才能继续使用应用程序的其他任何窗体
      if(SaveDialog.ShowDialog().Value)
      {
      using(StreamWrite moWrite = new StreamWrite(saveDialod.FileName))
      {
      //假死10秒,窗体可能会空白,标题显示无响应
      Thead.Sleep(10000);
      //假死之后提示文件保存成功!窗体恢复正常
      MessageBox.Show("保存成功!","提示");
      }
      }

37.进度条示例
      //添加一个processBar1,Max设为100;
      //添加一个timer1,Interval设为100;
      public Int32 mo=0;
      Timer1_Tick事件中写上
      {
      if(mo<101)
      {
      mo++;
      processBar1.Value=mo;
      }
      else
      {
      timer1.Stop();
      processBar1.Value=100;
      }
      }

38. 将文件复制进度显示在进度条上
      //需要拖一个ProcessBar1,一个Timer,1个Button1
      //点击Button1开始复制,
      //假设从C:/test.rar复制到C:/test/test.rar
      int hasCopy = 0; 
      FileStream fsRead = null; 
      FileStream fsWrite = null; 
      int fileLen = 0; 
      void Button1Click(object sender, EventArgs e) 
      { 
      string srcPath = @"C:/test.rar"; 
      string desPath = @"C:/test/test.rar"; 
      if(File.Exists(srcPath))
      { 
      fsRead = new FileStream (srcPath,FileMode.Open,FileAccess.ReadWrite); 
      fsWrite = new FileStream(desPath,FileMode.Create,FileAccess.ReadWrite); 
      fileLen = (int)fsRead.Length; 
      ProgreeBar1.Maximum = fileLen;
      byte[] buffer = new byte[1024]; 
      int len; 
      button1.Enabled= false; 
      timer1.Start(); 
      while((len = fsRead.Read(buffer,0,buffer.Length))>0)
      { 
      hasCopy += len; 
      fsWrite.Write(buffer,0,len); 
      fsWrite.Flush(); 
      }
      fsWrite.Close(); 
      fsRead.Close();
      }
      }
      private void Timer1Tick(object sender, EventArgs e) 
      { 
      if(fileLen > 0 && hasCopy <= fileLen)
      { 
      ProgreeBar1.Value = hasCopy;
      } 
      }

39.获取 鼠标的位置

1.   整个屏幕

textBox1.Text=System.Windows.Forms.Control.MousePosition.X.ToString();

textBox2.Text=System.Windows.Forms.Control.MousePosition.Y.ToString();

2.只应用于本窗体

Point myp = this.PointToScreen(e.Location);

this.Text = Convert.ToString(myp.X) + "  " + Convert.ToString(myp.Y);

40.获取当前文件所在的目录

MessageBox.Show(this,"当前执行程序所在的文件夹为:\n"+System.IO.Directory.GetCurrentDirectory()+"\n","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

41.获取特殊文件夹位置

系统文件夹:(windows\system32)this.textBox1.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.System);

程序文件夹:  this.textBox2.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);

桌面文件夹:  this.textBox3.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);

启动文件夹:  this.textBox4.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.Startup);

开始菜单文件夹:   this.textBox5.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.StartMenu);

我的音乐文件夹:   this.textBox6.Text=Environment.GetFolderPath(System.Environment.SpecialFolder.MyMusic);

42.只允许输入数字(文本框textbox)

privatevoid txtSum_KeyPress(object sender, KeyPressEventArgs e)

{

if ((e.KeyChar != 8 && !char.IsDigit(e.KeyChar))&&e.KeyChar!=13)

{

MessageBox.Show("商品数量只能输入数字","操作提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

e.Handled = true;

}

}

43.控制鼠标位置(引用API)

using System.Runtime.InteropServices;

[DllImport("User32.dll")]

privatestaticexternbool SetCursorPos(int x, int y);

privatevoid Form1_Load(object sender, EventArgs e)

{

SetPos();

}

privatestaticvoid SetPos()

{

int dx = 0;

int dy = 0;

SetCursorPos(dx, dy);

}

44.文本操作(txt保存,追加,读取)

1、建立一个文本文件

public class FileClass

{

public static void Main()

{

WriteToFile();

}

static void WriteToFile()

{

StreamWriter SW;

SW=File.CreateText("c:\MyTextFile.txt");

SW.WriteLine("God is greatest of them all");

SW.WriteLine("This is second line");

SW.Close();

Console.WriteLine("File Created SucacessFully");

}

}

2、读文件

public class FileClass

{

public static void Main()

{

ReadFromFile("c:\MyTextFile.txt");

}

static void ReadFromFile(string filename)

{

StreamReader SR;

string S;

SR=File.OpenText(filename);

S=SR.ReadLine();

while(S!=null)

{

Console.WriteLine(S);

S=SR.ReadLine();

}

SR.Close();

}

}

3、追加操作

public class FileClass

{

public static void Main()

{

AppendToFile();

}

static void AppendToFile()

{

StreamWriter SW;

SW=File.AppendText("C:\MyTextFile.txt");

SW.WriteLine("This Line Is Appended");

SW.Close();

Console.WriteLine("Text Appended Successfully");

}

}

打开:

richTextBox1.LoadFile(“c:\\1.txt”, RichTextBoxStreamType.PlainText);

保存:

richTextBox1.SaveFile(“c:\\1.txt”, RichTextBoxStreamType.PlainText);

45.文件夹文件操作(删除,创建)

using System.IO;

//创建文件夹

1.    if (!Directory.Exists("c:\\yinlikun\\abc\\abcd"))

{

Directory.CreateDirectory("c:\\yinlikun\\abc\\abcd");

}

2.Directory.CreateDirectory("c:\\adadsaaasda");

//删除文件夹

if (Directory.Exists("c:\\123"))

{

Directory.Delete ("c:\\123");

}

//创建文件

1.File.Create("c:\\aaa.txt");

2.

FileInfo fi = newFileInfo("C:\\ls.bmp");

if (!fi.Exists)

{

File.Create("C:\\ls.bmp");

}

//删除文件

FileInfo a = newFileInfo("C:\\1.txt");

if (a.Exists)

{

File.Delete("C:\\1.txt");

}

46.调用exe 文件

using System.Diagnostics;

Process p = new Process();

p.StartInfo.FileName = "cmd.exe";          //要调用的程序

p.StartInfo.UseShellExecute = false;       //关闭Shell的使用

p.StartInfo.RedirectStandardInput = true;  //重定向标准输入

p.StartInfo.RedirectStandardOutput = true; //重定向标准输出

p.StartInfo.RedirectStandardError = true;  //重定向错误输出

p.StartInfo.CreateNoWindow = true;         //设置不显示窗口

p.Start();

47.利用定时器在Label上间隔一段时间一行一行地显示文本文件中的内容
      //读取C:\test.txt中的内容按行隔一段时间显示到label1上为例
      string[] s = null;
      private int nline=0;
      s = File.ReadAllLines(@"c:\test.txt");
      private void timer1_Tick(object sender, EventArgs e)
      {
      if (nline < s.Length)
      {
      label1.Text = s[nline].ToString();
      }
      else
      {
      nline = 0;
      }
      nline = nline + 1;
      }

48. 利用DateTime.Now和DateTimePicker计算到某年某月某日还有多少天
      //date1,2格式化成你自己需要的格式
      DateTime date1 = DateTime.Now.Date; 
      DateTime date2 = dateTimePicker1.Value; 
      TimeSpan ts = date2 - date1; 
      MessageBox.Show(string.Format("距离{0}还有{1}天",date2, ts.TotalDays.ToString()));

49. .通过判断按下的按键来移动控件的位置
      //以移动Form1中的button1为例
      this.KeyPreview = true; 
      private void mainForm_KeyPress(object sender, KeyPressEventArgs e) 
      { 
      String moeKey = e.KeyChar.ToString(); 
      switch (moeKey) 
      { 
      case "w": button1.Top-=10; break; 
      case "s": button1.Top+=10; break; 
      case "a": button1.Left-=10; break; 
      case "d": button1.Left+=10; break; 
      } 
      }

50. 截取窗体保存成图片
      //以点击Form1中的button1截取Form1为例
      //用Graphics.CopyFromScreen()实现,4个参数
      Image memory = new Bitmap(this.Size.Width, this.Size.Height); 
      Graphics g = Graphics.FromImage(memory); 
      g.CopyFromScreen(this.Location.X,this.Location.Y,0,0,this.Size); 
      Clipboard.SetImage(memory); 
      String folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures); 
      string imagePath = folderPath+@"\mo"+DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second+"llyn23.jpg"; 
      memory.Save(imagePath, ImageFormat.Jpeg);

51. 拖动文件到窗体中,窗体中显示文件路径
      //以Form1为例,路径显示在label1上
      this.AllowDrop = true;
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      void Form1_DragDrop(object sender, DragEventArgs e)
      {
      string[] paths = e.Data.GetData(DataFormats.FileDrop) as string[];
      label1.Text = paths[0];
      }
      void Form1_DragEnter(object sender, DragEventArgs e)
      {
      if (e.Data.GetDataPresent(DataFormats.FileDrop))
      {
      e.Effect = DragDropEffects.Copy;
      }
      else
      {
      e.Effect = DragDropEffects.None;
      }
      }

52.把txt中的文本每行导入到listbox中

using System.IO;

string[] s = null;

privateint nline = 0;

privatevoid button1_Click(object sender, EventArgs e)

{

for (; nline < s.Length; nline++)

{

listBox1.Items.Add(s[nline].ToString());

}

}

privatevoid Form1_Load(object sender, EventArgs e)

{

s = File.ReadAllLines(@"c:\text.txt");

}

53.把listbox的每项导入到txt中(listbox text)

StreamWriter writer = newStreamWriter("abc.txt ", false, Encoding.Unicode);  //

for (int i = 0; i < listBox1.Items.Count; i++)

{

writer.WriteLine(listBox1.Items[i]);

}

writer.Close();

54.把屏幕截图附加到某个控件上

Graphics myg = pictureBox1.CreateGraphics();//pictureBox1控件

Size mys = new Size(1366, 768);

myg.CopyFromScreen(0, 0, 0, 0, mys);//截取屏幕的图像

myg.Dispose();

55.屏蔽任务管理器

File.OpenWrite(@"C:\WINDOWS\system32\taskmgr.exe");

56.列出文件夹下所有文件(包括路径)

string[] wenjian = Directory.GetFiles("C:\\sounds\\");

foreach (string a in wenjian)

{

listBox1.Items.Add(a);

}

57:释放内存的方法(代码加入定时器中,不断执行)

微软的 .NET FRAMEWORK 现在可谓如火如荼了。但是,.NET 一直所为人诟病的就是“胃口太大”,狂吃内存,虽然微软声称 GC 的功能和智能化都很高,但是内存的回收问题,一直存在困扰,尤其是 winform 程序,其主要原因是因为.NET程序在启动时,是需要由JIT动态编译并加载的,这个加载会把所有需要的资源都加载进来,很多资源是只有启动时才用的。
      以XP 系统为例子,程序启动后,打开任务管理器,会看到占用的内存量比较大,你把程序最小化,会发现该程序占用的内存迅速减小到一个很小的值,再恢复你的程序,你会发现内存占用又上升了,但是比你刚启动时的内存占用值还是小的,这就是一个资源优化的过程,这个过程是操作系统主动完成的。

每次都是写了之后回过头来才发现自己的代码很丑,系统架构师的作用就体现出来了。
      这里整理了一些网上关于Winform如何降低系统内存占用的资料,供参考,待更新:
      1、使用性能测试工具dotTrace 3.0,它能够计算出你程序中那些代码占用内存较多
      2、强制垃圾回收
      3、多dispose,close
      4、用timer,每几秒钟调用:SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);具体见附录。
      5、发布的时候选择Release
      6、注意代码编写时少产生垃圾,比如String + String就会产生大量的垃圾,可以用StringBuffer.Append
      7、this.Dispose();    this.Dispose(True);   this.Close();    GC.Collect();  
      8、注意变量的作用域,具体说某个变量如果只是临时使用就不要定义成成员变量。GC是根据关系网去回收资源的。
      9、检测是否存在内存泄漏的情况,详情可参见:内存泄漏百度百科
      致谢及附录:
      致谢:我可以感谢XiXiTV么,还有各种TV和桂电在线,还有感谢某某和某某们,自己想吧。
      附录:定期清理执行垃圾回收代码:
      //在程序中用一个计时器,每隔几秒钟调用一次该函数,打开任务管理器,你会有惊奇的发现
      #region 内存回收
      [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
      public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
      /// <summary>
      /// 释放内存
      /// </summary>
      public static void ClearMemory()
      {
      GC.Collect();
      GC.WaitForPendingFinalizers();
      if (Environment.OSVersion.Platform == PlatformID.Win32NT)
      {
      App.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
      }
      }
      #endregion

58.最小化其他窗口(所有窗口)

最小化所有窗口的方法:

添加引用 Microsoft Shell Controls and Automation
      Shell32.ShellClass sc = new Shell32.ShellClass(); 
      sc.MinimizeAll(); // Win+M 
      sc.UnminimizeAll(); // Shift+Win+M 
      IShellDispatch4 sd4 = (IShellDispatch4)sc; 
      if(sd4 != null) 
      sd4.ToggleDesktop(); // Win+D

这两行代码:

Shell32.ShellClass sc = new Shell32.ShellClass(); 
      sc.MinimizeAll(); // Win+M

即可最小化所有窗口,然后再把锁定窗口的WindowState设置成Normal即可。

而以下代码:

IShellDispatch4 sd4 = (IShellDispatch4)sc; 
      if(sd4 != null) 
      sd4.ToggleDesktop(); // Win+D

最小化所有窗口后,把锁定窗口的WindowState设置成Normal也无法把锁定窗口显示出来(所有窗口都被最小化了)

59.窗体透明控件不透明

Form f = newForm(); //创建一个新窗体

Label lab = newLabel();

privatevoid Form1_Load(object sender, EventArgs e)

{

f.FormBorderStyle = FormBorderStyle.None; //设置窗体无边框

f.ShowInTaskbar = false;

f.BackColor = Color.Red; f.TransparencyKey = f.BackColor; //让窗体透明

lab.Text = "我是在透明窗体上的不透明文本!";

lab.BackColor = Color.Transparent; //背景色透明

lab.Location = newPoint(100, 150); //调整在窗体上的位置

f.Controls.Add(lab);

f.TopLevel = true;

f.Show();

}

privatevoid Form1_Move(object sender, EventArgs e)

{

f.Location = this.Location;

}

60:打开一个新窗体关闭老窗体(建立一个新线程)

privatevoid button1_Click(object sender, EventArgs e)

{

newThread(show).Start();

this.Close();

}

void show()

{

Form2 abc = newForm2();

Application.Run(abc);

}

61:100内所有素数

62.//避免闪烁
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer |ControlStyles.ResizeRedraw |ControlStyles.AllPaintingInWmPaint, true);

63.MD5加密

有时我们的系统需要对用户的密码进行加密,则可以使用MD5加密算法,这在.net 2.0及以上版本中有,
      首先引入命名空间:
      using System.Security.Cryptography;
      然后可以编写一个通用的函数放到一个类中,下面给出全部的源代码:
      using System;
      using System.Security.Cryptography;
      using System.Text;
      namespace Common
      {
      class Md5
      {
      public static string MD5(string encryptString)
      {
      byte[] result = Encoding.Default.GetBytes(encryptString);
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] output = md5.ComputeHash(result);
      string encryptResult = BitConverter.ToString(output).Replace("-", "");
      return encryptResult;
      }
      }
      }
      使用时直接调用函数对字符串加密就行了
      string s1 = "123456";
      string s2 = Common.Md5.MD5(s1);
      则s2的值变为32的字符串:E10ADC3949BA59ABBE56E057F20F883E

64.窗体传值

Form1:

只需打开Form2即可

Form2:

Form1 f1;

public Form2(Form1 fm1)

{

f1 = fm1;

InitializeComponent();

}

privatevoid button1_Click(object sender, EventArgs e)

{

f1.textBox1.Text = textBox1.Text;

}

65. dataGridView1数据绑定.

string str = @"Data Source=JACK-PC\SQLEXPRESS;Database=netmusic;Integrated Security = SSPI;";

SqlConnection myconn = newSqlConnection(str);

myconn.Open();

String str2 = "select * from tb_musicInfo";

SqlDataAdapter myda = newSqlDataAdapter(str2, myconn);

DataTable myst = newDataTable();

myda.Fill(myst);

this.dataGridView1.DataSource = myst;

myconn.Close();

66.窗体只运行一次

1、

if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)

{

MessageBox.Show("程序已经运行了一个实例,该程序只允许有一个实例");

Application.Exit();

}

2、

string name = Process.GetCurrentProcess().MainModule.ModuleName;

string pname = Path.GetFileNameWithoutExtension(name);

Process[] myp = Process.GetProcessesByName(pname);

if (myp.Length > 1)

{

MessageBox.Show("对不起,本版本目前还不支持双开!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Stop);

this.Dispose(true);

Application.Exit();

return;

}

3、

using System.Threading;

publicstaticvoid Main(string[] args)

{

//声明互斥体。

Mutex mutex = newMutex(false, "ThisShouldOnlyRunOnce");

//判断互斥体是否使用中。

bool Running = !mutex.WaitOne(0, false);

if (!Running)

{

Application.Run(newForm1());

}

else

{

MessageBox.Show("应用程序已经启动!");

}

}

67.获取exe文件图标

System.Drawing.Icon.ExtractAssociatedIcon(string path)

68.c# 移动窗体和控件(拖动无标题窗体API)

using System.Runtime.InteropServices;

[DllImportAttribute("user32.dll")]

private extern static bool ReleaseCapture();

[DllImportAttribute("user32.dll")]

private extern static int SendMessage(IntPtr handle, int m, int p, int h);

protected void MyBaseControl_MouseDown(object sender, MouseEventArgs e)

{

if (e.Button == MouseButtons.Left)

{

this.Cursor = Cursors.SizeAll;

ReleaseCapture();

SendMessage(this.Handle, 0xA1, 0x2, 0);

this.Cursor = Cursors.Default;

}

}

//注:

如果用于运行时的某个控件,则可以把上面的代码放入此控件的MouseDown事件中,只是SendMessage(this.Handle, 0xA1, 0x2, 0);中的

this.Handle参数应改为此控件的Handle,如this.button1.Handle即可实现。

69.Repeater中绑定按钮(button、linkbutton...)

前台代码:

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">

<ItemTemplate>

<asp:Button ID="Button1" runat="server" CommandName="comButton1" CommandArgument='<%#Eval("ID") %>' Text='<%#Eval("Title") %>' />

</ItemTemplate>

</asp:Repeater>

后台代码:

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)

{

if (e.CommandName == "comButton1") //触发点击事件

{

int NewsID = int.Parse(e.CommandArgument.ToString()); //获取回发的值

InitPage(NewsID); //根据点击回发的值随便调用什么函数了

}

}

70.动态添加控件(动态批量添加控件,并添加事件)

添加控件:

CKB.CheckedChanged += new EventHandler(CKB_Click);

flowLayoutPanel1.Controls.Add(CKB);

事件定义:

private void CKB_Click(object sender, EventArgs e)

{

CheckBox CKB = (CheckBox)sender;

MessageBox.Show(CKB.Text);

}

71. C#中实现文本框的滚动条自动滚到最底端

1、配置textBox的Multiline属性为true;

2、配置textBox的ScrollBars属性为Vertical,实现纵向滚动条;

3、然后如下语句实现自己滚动:

private void textBox3_TextChanged_1(object sender, EventArgs e)

{

textBox3.SelectionStart = textBox3.Text.Length;

textBox3.ScrollToCaret();

}

72.字符串分割。

using System.Text.RegularExpressions;

string str="aaajsbbbjsccc";

string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);

foreach (string i in sArray) Response.Write(i.ToString() + "<br>");

73. 正则获取两个字符串中间的值

1)返回一条

///<summary>

///正则获取两个字符串中间的值

///</summary>

///<param name="str">源字符串</param>

///<param name="s">起始串</param>

///<param name="e">结束串</param>

///<returns></returns>

publicstaticstring GetValue(string str, string s, string e)

{

Regex rg = newRegex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);

return rg.Match(str).Value;

}

2)返回多条

privatevoid button1_Click(object sender, EventArgs e)

{

string str = "aa444444bbaa343434bbaa";

Regex r = newRegex(@"aa(?<name>.*?)bb");

MatchCollection m = r.Matches(str);

foreach (Match ma in m)

{

textBox2.Text+= ma.Groups["name"].Value + "\r\n";

}

}

74.解决“从客户端检测到有危险的Request.Form值”错误

平时在做网站建设的项目中,使用asp.net开发的时候,有时会遇到“从客户端检测到有潜在危险的Request.Form
值”的错误提示,查遍了本页程序也找不出错误的原因,实际正确解决方案应该是:

1、web.config文档<system.web>后面加入这一句: <pages validaterequest="false"/> 
      示例:
      <?xml version="1.0" encoding="gb2312" ?> 
      <configuration> 
      <system.web> 
      <pages validaterequest="false"/> 
      </system.web> 
      </configuration>

2、在*.aspx文档头的page中加入validaterequest="false",示例如下:
      <%@ page validaterequest="false" language="c#" codebehind="index.aspx.cs" autoeventwireup="false" inherits="mybbs.webform1" %> 
      .net framework 4.0的特点,在web.config的system.web节点里面加上<httpRuntime requestValidationMode="2.0" />就可以了。

75.ListView排序功能

类文件:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;//特别注意

using System.Windows.Forms;

namespace Mange

{

class ListViewSort : IComparer

{

private int col;

private bool descK;

public ListViewSort()

{

col = 0;

}

public ListViewSort(int column, object Desc)

{

descK = (bool)Desc;

col = column; //当前列,0,1,2...,参数由ListView控件的ColumnClick事件传递

}

public int Compare(object x, object y)

{

int tempInt = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);

if (descK) return -tempInt;

else return tempInt;

}

}

}

调用:

private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)

{

if (this.listView1.Columns[e.Column].Tag == null)

this.listView1.Columns[e.Column].Tag = true;

bool flag = (bool)this.listView1.Columns[e.Column].Tag;

if (flag) this.listView1.Columns[e.Column].Tag = false;

else this.listView1.Columns[e.Column].Tag = true;

this.listView1.ListViewItemSorter = new ListViewSort(e.Column, this.listView1.Columns[e.Column].Tag);

this.listView1.Sort();//对列表进行自定义排序

}