zoukankan      html  css  js  c++  java
  • C#.Net WinForm学习笔记

    .Net WinForm学习笔记

    1,MDI窗体
    设有两个窗体frmMain,frmChild,则:
    frmMain:  设IsMdiContainer属性为true
     打开子窗口:
      在相关事件中写如下代码:
      frmChild child=new frmChild();
      child.MdiParent=this;//this表示本窗体为其父窗体
      child.Show();
      在打开子窗体时,如果只允许有一个子窗体,可以加入如下判断:
      if (this.ActiveMdiChild!=null)
      {
         this.ActiveMdiChild.Close(); //关闭已经打开的子窗体
         //....
      }
    更改MDI主窗体背景
     先声明一个窗体对象
     private System.Windows.Forms.MdiClient m_MdiClient;
     在Form_Load等事件中,添加如下代码:
     int iCnt=this.Controls.Count;
     for(int i=0;i<iCnt;i++)
     {
     if(this.Controls[i].GetType().ToString()=="System.Windows.Forms.MdiClient")
     {
      this.m_MdiClient=(System.Windows.Forms.MdiClient)this.Controls[i];
      break;
     }
      }
     this.m_MdiClient.BackColor=System.Drawing.Color.Silver;
     具体可参见:http://cnblogs.com/Daview/archive/2004/05/06/8381.aspx

    2,创建系统托盘菜单
      2.1,创建一个contextMenu(cmnMain)菜单
      2.2,添加一个NotifyIcon组件,设置ContextMenu属性为cmnMain
      2.3,相应窗体改变事件(最小化等)
       private void frmMain_SizeChanged(object sender,EventArgs e)
       {
          if (this.WindowState==FormWindowState.Minimized)
          {
             this.Hide();
             noiMain.Visible=true;
          }
       }

      2.4,相应用户单击系统托盘上contextmenu菜单事件
      private void mniOpen(object sender,EventArgs e)
      {
          noiMain.Visible=false;
          this.Show();
          this.Focus();
      }

      2.5,响应用户双击系统托盘图标事件
      private void noiMain_DoubleClick(object s,EventArgs e)
      {
          minOpen.PerformClick(); //相当与mniOpen按钮的单击事件
      }
      **注意添加相应的事件句柄**

    3,创建不规则窗体
     3.1,在窗体上创建不规则图象,可以用gdi+绘制,或在图象控件上使用图象填充
     3.2,设置窗体的backcolor为colorA,然后设置TransparencyKey为colorA
     3.3,设置FormBorderStyle为none;

    4,创建顶部窗体
      this.TopMost=true;//把窗体的TopMost设置为true


    5,调用外部程序

      using System.Diagnostics

      Process proc=new Process();
      proc.StartInfo.FileName=@"notepad.exe";  //注意路径
      proc.StartInfo.Arguments="";
      proc.Start();

    //获得当前目录Directory.GetCurrentDirectory() (using System.IO)

    6,Toolbar的使用
      Toolbar控件通常需要imagelist控件结合使用(需要用到其中图标)
      响应Toolbar单击事件处理程序代码:
      switch(ToolbarName.Buttons.IndexOf(e.Button))
      {
          case 0:   //第一个按钮
              //code ...
              break;
          case 1:   //第二个按钮
              //code ...
              break;
          //other case code
          default:  //默认处理,但以上所有项都不符合时
              //code ...
              break;
      }

    7,弹出对话框获得相关返回值
      在窗体的closing事件中运行如下代码,可以在用户关闭窗体时询问
      DialogResult result=MessageBox.Show(this,"真的要关闭该窗口吗?","关闭提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
      if (result==DialogResult.OK)
      {
      //关闭窗口
      e.Cancel=false;
      }
      else
      {
      //取消关闭
      e.Cancel=true;
      }

    8,打印控件
      最少需要两个控件
      PrintDocument
      PrintPreviewDialog:预览对话框,需要printdocument配合使用,即设置document属性为
                         对应的printDocument
      printdocument的printpage事件(打印或预览事件处理程序)代码,必须.

     float fltHeight=0;
     float fltLinePerPage=0;
     long lngTopMargin=e.MarginBounds.Top;
     int intCount=0;
     string strLine;

     //计算每页可容纳的行数,以决定何时换页
     fltLinePerPage=e.MarginBounds.Height/txtPrintText.Font.GetHeight(e.Graphics);

       
     while(((strLine=StreamToPrint.ReadLine()) != null) && (intCount<fltLinePerPage))
     {
        intCount+=1;
        fltHeight=lngTopMargin+(intCount*txtPrintText.Font.GetHeight(e.Graphics));
        e.Graphics.DrawString(strLine,txtPrintText.Font,Brushes.Green,e.MarginBounds.Left,fltHeight,new StringFormat());
     }

     //决定是否要换页
     if (strLine!=null)
     {
        e.HasMorePages=true;
     }
     else
     {
        e.HasMorePages=false;
     }
      以上代码的StreamToPrint需要声明为窗体级变量:
      private System.IO.StringReader StreamToPrint;

      打开预览对话框代码(不要写在printpage事件中)
      StreamToPrint=new System.IO.StringReader(txtPrintText.Text);
      PrintPreviewDialogName.ShowDialog();

    9,string对象本质与StringBuilder类,字符串使用
    string对象是不可改变的类型,当我们对一个string对象修改后将会产生一个新的string对
    象,因此在需要经常更改的字符对象时,建议使用StringBuilder类:
    [范例代码]构造一个查询字符串
    StringBuilder sb=new StringBuilder("");
    sb.Append("Select * from Employees where ");
    sb.Append("id={0} and ");
    sb.Append("title='{1}'");
    String cmd=sb.ToString();

    sb=null; //在不再需要时清空它

    cmd=String.Format(cmd,txtId.Text,txtTile.Text); //用实际的值填充格式项

    判断字符串是否为空:
    检查一个字符串是否为空或不是一个基本的编程需要,一个有效的方法是使用string类的Length属性来取代使用null或与""比较。

    比较字符串:使用String.Equals方法来比较两个字符串
    string str1="yourtext";
    if (str1.Equals("TestSting") )
    {
      // do something
    }

    10,判断某个字符串是否在另一个字符串(数组)中
     需要用到的几个方法
     string.Split(char);//按照char进行拆分,返回字符串数组
     Array.IndexOf(Array,string):返回指定string在array中的第一个匹配项的下标
     Array.LastIndexOf(Array,string):返回指定string在array中的最后一个匹配项的下标
     如果没有匹配项,则返回-1
     [示例代码]:
     string strNum="001,003,005,008";
     string[] strArray=strNum.Split(',');//按逗号拆分,拆分字符为char或char数组
     
     Console.WriteLine(Array.IndexOf(strArray,"004").ToString());

    11,DataGrid与表和列的映射
    从数据库读取数据绑定到DataGrid后,DataGrid的列标头通常跟数据库的字段名相同,如果
    不希望这样,那么可以使用表和列的映射技术:
    using System.Data.Common;

    string strSql="select * from Department";
    OleDbDataAdapter adapter=new OleDbDataAdapter(strSql,conn);

    DataTableMapping dtmDep=adapter.TableMappings.Add("Department","部门表");

    dtmDep.ColumnMappings.Add("Dep_Id","部门编号");
    dtmDep.ColumnMappings.Add("Dep_Name","部门名称");

    DataSet ds=new DataSet();

    adapter.Fill(ds,"Department"); //此处不能用"部门表"

    响应单击事件(datagrid的CurrentCellChanged事件)
    DataGridName.CurrentCell.ColumnNumber;//所单击列的下标,从0开始,下同
    DataGridName.CurrentCell.RowNumber;//所单击行的下标
    DataGridName[DataGridName.CurrentCell];//所单击行和列的值

    DataGridName[DataGridName.CurrentRowIndex,n].ToString();//获得单击行第n+1列的值

    12,动态添加菜单并为其添加响应事件
     添加顶级菜单:
     MainMenuName.MenuItems.Add("顶级菜单一");//每添加一个将自动排在后面

     添加次级菜单:
     MenuItem mniItemN=new MenuItem("MenuItemText")
     MenuItem mniItemN=new MenuItem("MenuItemText",new EventHandler(EventDealName))
     MainMenuName.MenuItems[n].MenuItems.Add(mniItemN);//n为要添加到的顶级菜单下标,从0开始

     创建好菜单后添加事件:
     mniItemN.Click+=new EventHandler(EventDealName);

     也可以在添加菜单的同时添加事件:
     MenuItem mniItemN=new MenuItem("MenuItemText",new EventHandler(EventDealName));
     MainMenuName.MenuItems[n].MenuItems.Add(mniItemN);

    13,正则表达式简单应用(匹配,替换,拆分)
     using System.Text.RegularExpressions;

     //匹配的例子
     string strRegexText="你的号码是:020-32234102";
     string filter=@"d{3}-d*";

     Regex regex=new Regex(filter);
     Match match=regex.Match(strRegexText);

     if (match.Success) //判断是否有匹配项
     {
         Console.WriteLine("匹配项的长度:"+match.Length.ToString());
         Console.WriteLine("匹配项的字符串:"+match.ToString());
         Console.WriteLine("匹配项在原字符串中的第一个字符下标:"+match.Index.ToString());
     }
     
     //替换的例子
     string replacedText=regex.Replace(strRegexText,"020-88888888");
     Console.WriteLine(replacedText);//输出"你的号码是:020-88888888"

     //拆分的例子
     string strSplitText="甲020-32654已020-35648丙020-365984";
     foreach(string s in regex.Split(strSplitText))
     {
        Console.WriteLine(s); //依次输出"甲乙丙"
     }

    13,多线程简单编程
     using System.Threading;

     Thread ThreadTest=new Thread(new ThreadStart(ThreadCompute));
     ThreadTest.Start();//使用另一个线程运行方法ThreadCompute
     
     ThreadCompute方法原型:
     private void ThreadCompute()
     {}

    14,操作注册表
    using System.Diagnostics;
    using Microsoft.Win32;
      //操作注册表
      RegistryKey RegKey=Registry.LocalMachine.OpenSubKey("Software",true);

      //添加一个子键并给他添加键值对
      RegistryKey NewKey=RegKey.CreateSubKey("regNewKey");
      NewKey.SetValue("KeyName1","KeyValue1");
      NewKey.SetValue("KeyName2","KeyValue2");

      //获取新添加的值
      MessageBox.Show(NewKey.GetValue("KeyName1").ToString());

      //删除一个键值(对)
      NewKey.DeleteValue("KeyName1");

      //删除整个子键
      RegKey.DeleteSubKey("regNewKey");

    引用:https://www.cnblogs.com/jxsoft/archive/2011/04/28/2032053.html

    HK
  • 相关阅读:
    【BZOJ 4151 The Cave】
    【POJ 3080 Blue Jeans】
    【ZBH选讲·树变环】
    【ZBH选讲·拍照】
    【ZBH选讲·模数和】
    【CF Edu 28 C. Four Segments】
    【CF Edu 28 A. Curriculum Vitae】
    【CF Edu 28 B. Math Show】
    【CF Round 439 E. The Untended Antiquity】
    【CF Round 439 C. The Intriguing Obsession】
  • 原文地址:https://www.cnblogs.com/HarryK4952/p/14461929.html
Copyright © 2011-2022 走看看