WinForm開發常用小知識

    最近由於工作需要,開發了一個公司內部用於支持反射獲得窗體信息並保持爲XML的小工具,期間用到了好多很簡單的WinForm開發常用小知識,但是由於以前很少做WinFrom開發,所以用到這些小知識的時候就只好現做現查。工作完成後本想自己總結下,但是由於工作日程實在是太緊張了,只好從把別人總結的拉過來,以備不時之需。

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開始

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章