WinForm学习笔记(2)
?
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");
?
總結
以上是生活随笔為你收集整理的WinForm学习笔记(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最简单的制作从USB启动的系统的方法
- 下一篇: C++ 的变量书写规则探讨