C#基礎


類型和變量

類型

C# 支持兩種類型:“值類型”和“引用類型”。值類型包括簡單類型(如 char、int 和 float等)、枚舉類型和結構類型。引用類型包括類 (Class)類型、接口類型、委托類型和數組類型。

變量的類型聲明

每個變量必須預先聲明其類型。如

int a;

     int b = 100;

     float j = 4.5;

string s1;

用object可以表示所有的類型。

預定義類型

下表列出了預定義類型,並說明如何使用。

類型

說明

示例

范圍

object

所有其他類型的最終基類型

object o = null;

 

string

字符串類型;字符串是 Unicode 字符序列

string s = "hello";

 

sbyte

8 位有符號整型

sbyte val = 12;

-128 到 127

short

16 位有符號整型

short val = 12;

-32,768 到 32,767

int

32 位有符號整型

int val = 12;

-2,147,483,648 到 2,147,483,647

long

64 位有符號整型

long val1 = 12;

long val2 = 34L;

-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807

byte

8 位無符號整型

byte val1 = 12;

0 到 255

ushort

16 位無符號整型

ushort val1 = 12;

0 到 65,535

uint

32 位無符號整型

uint val1 = 12;

uint val2 = 34U;

0 到 4,294,967,295

ulong

64 位無符號整型

ulong val1 = 12;

ulong val2 = 34U;

ulong val3 = 56L;

ulong val4 = 78UL;

0 到 18,446,744,073,709,551,615

float

單精度浮點型

float val = 1.23F;7位

±1.5 × 10−45 到 ±3.4 × 1038

double

雙精度浮點型

double val1 = 1.23;

double val2 = 4.56D;15-16

±5.0 × 10−324 到 ±1.7 × 10308

bool

布爾型;bool 值或為真或為假

bool val1 = true;

bool val2 = false;

 

char

字符類型;char 值是一個 Unicode 字符

char val = 'h';

 

decimal

精確的小數類型,具有 28 個有效數字

decimal val = 1.23M;28-29

±1.0 × 10−28 到 ±7.9 × 1028

DateTime

 

 

 

 

變量轉換

簡單轉換:

float f = 100.1234f;

可以用括號轉換:

short s = (short)f

也可以利用Convert方法來轉換:

string s1;

     s1=Convert.ToString(a);

MessageBox.Show(s1);

常用Convert方法有:

C#

備注

Convert.ToBoolean

 

Convert.ToByte

 

Convert.ToChar

 

Convert.ToDateTime

 

Convert.ToDecimal

 

Convert.ToDouble

 

Convert.ToInt16

 

Convert.ToInt32

 

Convert.ToInt64

 

Convert.ToSByte

 

Convert.ToSingle

 

Convert.ToString

 

Convert.ToUInt16

 

Convert.ToUInt32

 

Convert.ToUInt64

 

Math類

常用科學計算方法:

C#

備注

Math.Abs

絕對值

Math.Sqrt

開方

Math.Round

取整,四舍五入

Math.Floor

取整,放棄小數

Math.Cos

余弦

Math.Sin

正弦

Math.Tan

正切

Math.Exp

返回e的指定次冪

Math.Log

對數

Math.Pow(x,y)

數字xy次冪

Math.Max(x,y)

返回較大者

Math.Min(x,y)

返回較小者

 

 

枚舉型

一般為字符串,可以定義帶數字的枚舉型,示例為:

         enum Color

         {

              Red=1,

              Blue=2,

              Green=3

         }

         class Shape

         {

              public int Fill(Color color)

              {

                   int ii;

                   switch(color)

                   {

                       case Color.Red:

                            ii=10;

                                 break;

                       case Color.Blue:

                            ii=11;

                                 break;

                       case Color.Green:

                            ii=12;

                                 break;

                       default:

                            ii=-1;

                            break;

                   }

                   return ii;

              }

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              int i;

              Shape s1=new Shape();

              i=s1.Fill((Color)2);  

              //i=s1.Fill(Color.Blue);   

              MessageBox.Show(i.ToString());  

     }

Enum需要放在class外面,才能被其它class的程序調用。

C#關鍵字

abstract

event

new

struct

as

explicit

null

switch

base

extern

object

this

bool

false

operator

throw

break

finally

out

true

byte

fixed

override

try

case

float

params

typeof

catch

for

private

uint

char

foreach

protected

ulong

checked

goto

public

unchecked

class

if

readonly

unsafe

const

implicit

ref

ushort

continue

in

return

using

decimal

int

sbyte

virtual

default

interface

sealed

volatile

delegate

internal

short

void

do

is

sizeof

while

double

lock

stackalloc

 

else

long

static

 

enum

namespace

string

 

 

數組

定義

數組是一種排列有序的數據結構,包含於數組中的變量被稱為數組的元素,它們都有相同的類型。

數組聲明

int [] array1 = new int[5];

int [,,] array3 = new int[10,20,30];

int [] array1 = new int[] {1,2,4};

數組引用

array1[0]="a1";

注意,如果定義數組為int[5] ,則從0~4。

數組長度

line0.GetLength(1)

數組賦值

可以從一個已經賦值的數組array2向未賦值的同等數組array1賦值,用

array1=array2;

這時,array1就變成和array2一樣的數組了。

集合

集合的使用

集合可以看成是可以隨意添加的數組,因此凡是在使用數組的場合,都可以使用集合。而且集合的元素可以是任意對象,操作也比數組靈活的多。

使用集合時,必須注意集合的生命期問題。如果有兩個集合L1和L2,使用了

L1=L2;

后,只要L2生命期沒有終結,它的以后的變化就可能會影響到L1的數值。因此在賦值后應該及時銷毀或者初始化L2,以免發生不可預見的錯誤。

比較

使用Contains方法。

      ArrayList Array1=new ArrayList();

      Array1.Add("as");

      bool b1=Array1.Contains("as");

      MessageBox.Show(b1.ToString());      

找到集合中數量最多的一個元素

利用方法來查找,可以返回兩個變量。

         object Jmax0(ArrayList v11,ref int jj)

         {

              int i;

              object j0=0;

              ArrayList y11=new ArrayList(); //各個不同的元素的集合

              int [] y12=new int[v11.Count]; //記錄各個元素數量的數組         

              int xmax=0; //最大的一個元素的數量

 

              for (i=0;i<v11.Count;i++)

              {

                   j0=(object)v11[i];

                   if (y11.Contains(j0))

                   {

                       y12[y11.IndexOf(j0)]++;

                   }

                   else

                   {                     

                       y11.Add(j0);

                       y12[y11.Count-1]=1;

                   }                 

              }

 

              xmax=y12[0];

              j0=(object)y11[0];

              for (i=1;i<y11.Count;i++)

              {

                   if(y12[i]>xmax)

                   {

                       xmax=y12[i];

                       j0=(object)y11[i];

                   }

              }

              jj=xmax;

              return j0;

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              ArrayList Array1=new ArrayList();

              int jj=0;

              double j0=0;

              object j1=0;

             

              j0=2.3;

              Array1.Add(j0);   

              j0=2.3;

              Array1.Add(j0);   

              j0=1.000f;

              Array1.Add(j0);

              j0=2.3;

              Array1.Add(j0);   

              j0=1;

              Array1.Add(j0);

              j1=Jmax0(Array1,ref jj);

              MessageBox.Show(j1.ToString()+" "+jj.ToString());

         }

運算符和判斷

判斷

if (x > 10)

 if (y > 20)

  Console.Write("Statement_1");

 else

  Console.Write("Statement_2");

關系運算符

<,<=,>,>=

等於:==

不等於:!=

判斷字符串string和char用Equals方法。

邏輯運算符

與:a & b

或:a | b

非:! A

模數運算符

模數運算符 (%) 計算第二個操作數除第一個操作數后的余數。所有數值類型都具有預定義的模數運算符。如

Console.WriteLine(5 % 2);       // =1

Console.WriteLine(-5 % 2);      // =-1

Console.WriteLine(5.0 % 2.2);   // =0.6

Console.WriteLine(-5.2 % 2.0);  // =-1.2

經常用模數運算符來判斷整數為奇數(=1)或偶數(=0)。

循環

無條件循環

int sum,x;

              sum=0;

              for(x=1;x<=100;x++)

              {

                   sum+=x;

              }

有條件循環

private void button1_Click(object sender, System.EventArgs e)

         {

              int sum=0;

              int x=0;

              while ((sum<100) & (x<20))

              {

                   x++;

                   sum+=x;

              }

              string s2=Convert.ToString(x);

              MessageBox.Show(s2);

     }

運行顯示14。

如果改為

          while ((sum<100) | (x<20))

運行顯示20。

多重選擇

switch (i)

{

case 0:

 CaseZero();

 break;

case 1:

 CaseOne();

 break;

default:

 CaseOthers();

 break;

}

每個case后面,必須有break或者goto,不允許貫穿。

Goto

goto 語句將程序控制直接傳遞給標記語句。

for (int i = 0; i < x; i++)

   for (int j = 0; j < y; j++)

    if (myArray[i,j].Equals(myNumber))

     goto Found;

 

  Console.WriteLine("The number {0} was not found.", myNumber);

  goto Finish;

 

 Found:

  Console.WriteLine("The number {0} is found.", myNumber);

 

 Finish:

  Console.WriteLine("End of search.");

foreach

foreach 語句為對數組或者集合中的每個元素重復執行嵌入語句。對於數組示例為:

using System;

class MainClass

{

   public static void Main()

   {

      int odd = 0, even = 0;

      int[] arr = new int [] {0,1,2,5,7,8,11};

 

      foreach (int i in arr)

      {

         if (i%2 == 0) 

            even++;     

         else

            odd++;        

      }

 

      Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",

                        odd, even) ;

   }

}

break

退出當前的循環。

也可以退出當前模塊,使用一個空while循環,示例如下:

         void CH(double X1)

         {

              bool bl=true;

              while (bl)

              {

                   if (X1==1.0)

                   {

                       MessageBox.Show("YES");

                       break;

                   }

                   MessageBox.Show("no");

                   bl=false;

              }

         }

 

輸出格式

簡單格式

對於控制台程序:

Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",odd, even) ;

對於普通系統:

int x=1,y=2;

string s0;

s0=string.Format("Found {0} Odd Numbers, and {1} Even Numbers.",x, y);

MessageBox.Show(s0);

format

用指定字符和數字說明格式。C(貨幣格式,用NumberFormatInfo指定種類)D(十進制整數)E(科學計數法)F(固定點)G(常規)N(數字)P(百分比)等。

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");

double MyDouble = 123456789;

Console.WriteLine(MyDouble.ToString("C1"));

Console.WriteLine(MyDouble.ToString("E"));

Console.WriteLine(MyDouble.ToString("P"));

Console.WriteLine(MyDouble.ToString("N3"));

Console.WriteLine(MyDouble.ToString("F"));

運行顯示:

$123,456,789.0

1.234568E+008

12,345,678,900.00%

123,456,789.000

123456789.00

還可以這樣使用:

String.Format("{0:F2} {1:F2} {2:F2}", x,y,z)

控制台程序

打開Visual C# .NET 2003,選擇【新建】/【項目】,或者選擇【新建項目】在Visual C#項目中選擇【控制台應用程序】,選擇程序名稱和位置后,進入程序界面(IDE)。

 

這時系統生成一個class1.cs的程序文件。修改成以下:

using System;

namespace Console2

{

     // A "Hello World!" program in C#

     class Hello

     {

         static void Main()

         {

              Console.WriteLine("Hello World!");

         }

     }

}

點擊【調試】/【開始執行(不調試)】,就可以在DOS界面下看見結果。

 

 

二、使用控件

基本操作

添加控件

選擇程序名稱和位置后,進入程序的一個Form1界面。

從左邊的【工具箱】/【Windows窗體】中,添加一個Label控件和一個Button控件,雙擊Button1,添加程序如下:

private void button1_Click(object sender, System.EventArgs e)

         {

              label1.Text="iiii";

     }

就可以查看運行效果了。

如果修改成

label1.Left=label1.Left+10;

就可以看見點擊Button后,標簽右移的效果。

控件的基本特性

工具箱的控件主要有Button(按鈕)、Label(標簽)、TextBox(文本框)、RadioButton(單選按鈕)、CheckBox(復選框)、ListBox(下拉框)等。

可以雙擊在Form上產生控件,也可以先點擊,然后在Form上畫矩形,決定控件的大小。

控件的基本特性有事件、方法和屬性,詳見2.2。

控件的事件主要有Click(單擊)、DoubleClick(雙擊)、MouseOver(鼠標移過)等。

控件的方法主有Focus(聚焦)、Hide(隱藏)、Show(顯示)等。

控件的主要屬性有:

1.尺寸控制,主要有Width(寬度)、Height(高度)等;

2.位置控制,主要有Left(左邊界)、Top(上邊界)等;

3.顏色和字體控制,主要有BackColor(背景顏色)、ForeColor(前景顏色)、Font(字體)等;

4.名稱控制,主要有Name(控件名字)、Caption(控件標題)等;

5.控件序號,主要有TabIndex(焦點的TAB順序控制)、Index(控件數組序號);

6.其它,主要有Enabled(決定控件是否激活,True或 False)、ToolTipText(鼠標移過時顯示的文字)等。

消息框MessageBox

簡單使用方法

使用消息框,可以在程序運行到這里時彈出一個對話框,顯示指定的文字。是向外輸出信息的重要方式。

MessageBox.Show("def");

 

通用方法

消息框輸出必須為string類型,如果不是,則需要轉換:

string s1;

     s1=Convert.ToString(a);

MessageBox.Show(s1);

可以用以下函數簡化使用方法:

private void msgbox(object a) //用消息框顯示任意一個數

         {

              string s1;

              s1=Convert.ToString(a);

              MessageBox.Show(s1);

     }

較多使用方法

MessageBox.Show("name", "Name Entry", MessageBoxButtons.OK, MessageBoxIcon . Exclamation);

其中第二項開始依次為消息框的標題、按鈕樣式、圖標樣式。

MessageBoxButtons的數值為枚舉型,為OK(缺省)、AbortRetryIgnore、OKCancel、RetryCancel、YesNo、YesNoCancel。

獲取返回信息

         private void button2_Click(object sender, System.EventArgs e)

         {

              DialogResult result;

              result = MessageBox.Show("name", "Name Entry", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

              MessageBox.Show(result.ToString());                    

     }

如果要參與判斷,則用

string ls=result.ToString();

完全使用方法

本例檢查textBox1中輸入文本沒有,如果沒有就提示,並可以獲取返回信息。

         private void button1_Click(object sender, System.EventArgs e)

         {

              if(textBox1.Text.Length == 0)

              {

                   string message = "You did not enter a server name. Cancel this operation?";

                   string caption = "No Server Name Specified";

                   MessageBoxButtons buttons = MessageBoxButtons.YesNo;

                   DialogResult result;

 

                   result = MessageBox.Show(this, message, caption, buttons,

                       MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,

                       MessageBoxOptions.RightAlign);

 

                   if(result == DialogResult.Yes)           

                       this.Close();

                   }

              }

     }   

 

文本框

基本功能

文本框主要是用來輸入和顯示文字的。

添加一個TextBox,系統自己產生名字textBox1,程序如下:

private void button1_Click(object sender, System.EventArgs e)

         {

              MessageBox.Show(textBox1.Text); 

     }

運行時,就可以在消息框中顯示文本框輸入的字符串。

TextBox一般顯示單行,如果把屬性Multiline改為Ture,還可以顯示多行數字。

輸入數字

輸入數字需要轉換:

int a;

              string s1;

              a=Convert.ToInt16(textBox1.Text);

              a=a+5;

              s1=Convert.ToString(a);

          MessageBox.Show(s1);  

初始化

文本框的初始化就是向文本框賦初始值。可以從事件過程里寫入,也可以在IDE的右邊屬性欄里輸入,但是推薦采用在Form初始化時寫入。

public Form1()

     {

         InitializeComponent();

         // TODO: 在 InitializeComponent 調用后添加任何構造函數代碼

         textBox1.Text="";

}

窗體調用

簡單調用

上面的例子都是在一個窗體中,實際程序需要幾十甚至上百個窗體。以下例子創建兩個窗體,然后實現相互調用。

在Form1中添加兩個Button,一個標題為調用,一個標題為退出。

使用【項目】/【添加窗體】,添加一個窗體,缺省名稱為Form2。添加一個Button,標題為返回。

窗體1程序為:

private void button1_Click(object sender, System.EventArgs e)

         {

              Form2 Nform2=new Form2();

              Nform2.Show();

              this.Hide();

         }

 

         private void button2_Click(object sender, System.EventArgs e)

         {

              Application.Exit();

     }

窗體2程序為:

private void button1_Click(object sender, System.EventArgs e)

         {

              Form1 Nform1=new Form1();

              Nform1.Show();

              this.Hide();

     }

運行程序,可以在兩個窗體之間來回調用,按“退出”就可以退出程序。

程序運行時,如果發現窗體位置不固定,這時需要在窗體的StartPosition屬性上設置窗體固定位置,一般為屏幕中央。

注意,兩個窗體要在一個命名空間,否則要引用。

傳遞參數調用

在Form1中添加一個Button1和一個textBox1,程序為:

private Form2 otherForm=new Form2();

         private void GetOtherFormTextBox()

         {

              textBox1.Text = otherForm.TextBox1.Text;

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              GetOtherFormTextBox();

     }

在Form2中添加一個textBox1,在

InitializeComponent();

后面添加一個賦值語句為:

     textBox1.Text="abd";

然后添加一個屬性:

         public TextBox TextBox1

         {

              get

              {

                   return textBox1;

              }

     }

運行時,點擊Form1中的Button1,可以把Form2的TextBox的數值取到Form1的TextBox中來。

復雜傳遞參數

本例是移動一個標簽,在兩個Form之間來回移動。

先設計Form1如下:

 

設計Form2,除了少了一個退出按鈕外,其余相同。

在Form1的InitializeComponent()下面加上窗體定位語句:

Point tempPoint = new Point(100,100);

          this.DesktopLocation = tempPoint;

然后把Form1的StartPosition屬性改為Manual。其余程序為:

 

         public Label L2

         {

              get

              {

                   return label1;

              }

              set

              {

                   label1=value;

              }

         }

        

         private void button2_Click(object sender, System.EventArgs e)

         {

              Form2 otherForm=new Form2();

              label1.Left=label1.Left+10;

              if (label1.Left>=this.Width-10)

              {

                   otherForm.Show();

                   otherForm.L1.Top=label1.Top;

                   this.Hide();

              }

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              label1.Left=label1.Left-10;

         }

 

         private void button3_Click(object sender, System.EventArgs e)

         {

              label1.Top=label1.Top-10;

         }

 

         private void button4_Click(object sender, System.EventArgs e)

         {

              label1.Top=label1.Top+10;

         }

 

         private void button5_Click(object sender, System.EventArgs e)

         {

              Application.Exit();

     }

同樣在Form2的InitializeComponent()下面加上窗體定位語句:

Point tempPoint = new Point(300,100);

          this.DesktopLocation = tempPoint;

然后把Form2的StartPosition屬性改為Manual。其余程序為:

         public Label L1

         {

              get

              {

                   return label1;

              }

              set

              {

                   label1=value;

              }

         }

        

         private void button2_Click(object sender, System.EventArgs e)

         {

              label1.Left=label1.Left+10;

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              Form1 otherForm1=new Form1();

              label1.Left=label1.Left-10;

              if (label1.Left<=-10)

              {

                   otherForm1.Show();

                   otherForm1.L2.Top=label1.Top;

                   otherForm1.L2.Left=otherForm1.Width-20;

                   this.Hide();

              }

         }

 

         private void button3_Click(object sender, System.EventArgs e)

         {

              label1.Top=label1.Top-10;

         }

 

         private void button4_Click(object sender, System.EventArgs e)

         {

              label1.Top=label1.Top+10;

     }

動態產生窗體

         public void CreateMyForm()

         {

              Form form1 = new Form();

              Label label1 = new Label();

              Button button1 = new Button ();

              TextBox text1 = new TextBox();

             

              button1.Text = "確定";

              button1.Location = new Point (110, 220);

              label1.Location = new Point (50,100);

              text1.Location = new Point (150,100);

 

              form1.Text = "請輸入";

              label1.Text = "數據";

              form1.FormBorderStyle = FormBorderStyle.FixedDialog;

              form1.ControlBox = false;

              form1.CancelButton = button1;            

              form1.StartPosition = FormStartPosition.CenterScreen;

  

              form1.Controls.Add(button1);

              form1.Controls.Add(text1);

              form1.Controls.Add(label1);

  

              form1.ShowDialog();

              ls=text1.Text;

         }

        

         private void button2_Click(object sender, System.EventArgs e)

         {            

              CreateMyForm();

              MessageBox.Show(ls);                     

     }

ToolBar

普通使用

在窗體上加上ToolBar

 

界面修改后的問題

在界面上修改后,最后要加上:

              toolBar1.Buttons.Add(toolBarButton1);

              toolBar1.Buttons.Add(toolBarButton2);

              toolBar1.Buttons.Add(toolBarButton3);

   

              // Add the event-handler delegate.

          toolBar1.ButtonClick += new ToolBarButtonClickEventHandler (this.toolBar1_ButtonClick);

或者把原有的程序

this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {

              this.toolBarButton1,this.toolBarButton2,this.toolBarButton3});

改變位置,到toolBar1設置的最下面。

全部設置程序為:

              this.toolBar1.DropDownArrows = true;

              this.toolBar1.Location = new System.Drawing.Point(0, 0);

              this.toolBar1.Name = "toolBar1";

              this.toolBar1.ShowToolTips = true;

              this.toolBar1.Size = new System.Drawing.Size(592, 42);

              this.toolBar1.TabIndex = 0;

              toolBar1.ButtonSize = new System.Drawing.Size(60, 50);

              //

              // toolBarButton1

              //

              this.toolBarButton1.Text = "Open";

              toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;

              //

              // toolBarButton2

              //

              this.toolBarButton2.Text = "Save";

              toolBarButton2.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;

              //

              // toolBarButton3

              //

              this.toolBarButton3.Text = "Print";

 

              toolBar1.Buttons.Add(toolBarButton1);

              toolBar1.Buttons.Add(toolBarButton2);

          toolBar1.Buttons.Add(toolBarButton3);

          toolBar1.ButtonClick += new ToolBarButtonClickEventHandler (this.toolBar1_ButtonClick);

設置按鈕大小

如下設置,可以正常居中顯示9號字體。

toolBar1.ButtonSize = new System.Drawing.Size(60, 50);

用程序實現

可以用程序實現按鈕的增加,但是無法全部實現自動化。

先需要手工添加toolBar1和imageList1,然后把imageList1中的圖片一一加上。

        void toolBarSet()

        {

            //添加按鈕           

            ToolBarButton toolBarButton1=new ToolBarButton();

            ToolBarButton toolBarButton2=new ToolBarButton();      

            toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { toolBarButton1,toolBarButton2});

            toolBar1.DropDownArrows = true;

            toolBar1.ImageList = imageList1;           

            toolBar1.Size = new System.Drawing.Size(408, 37);

            toolBar1.TabIndex = 0;           

            toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(toolBar1_ButtonClick);

            // toolBarButton1

            toolBarButton1.ImageIndex = 0;

            toolBarButton1.ToolTipText = "放大";

            // toolBarButton2

            toolBarButton2.ImageIndex = 1;

            toolBarButton2.ToolTipText = "縮小";

        }

 

        private void Form1_Load(object sender, System.EventArgs e)

        {

            toolBarSet();

        }

 

        private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)

        {

            switch(toolBar1.Buttons.IndexOf(e.Button))

            {

                case 0:  //放大

                    MessageBox.Show("放大");               

                    break;

                case 1:  //縮小

                    MessageBox.Show("縮小"); 

                    break;

               

                default:

                    MessageBox.Show("other");

                    break;

            }    

        }

 

listBox

普通調用

在窗體上放置一個listBox1,一個button1和一個label1。以下程序實現添加選項,雙擊選項就可以顯示你的選擇:

        private void button1_Click(object sender, System.EventArgs e)

        { 

            listBox1.Items.Clear();

            listBox1.Items.Add("");

            listBox1.Items.Add("選擇1");

            listBox1.Items.Add("選擇2");

            listBox1.SelectedIndex=0;

        }

 

        private void listBox1_DoubleClick(object sender, System.EventArgs e)

        {

            Label1.Text=listBox1.SelectedIndex.ToString();

        }

第一項是一個缺省空項,允許用戶不選取退出。

Items是一個集合,因此增減選項可以按照集合那樣操作。

用數組添加選項

System.Object[] ItemObject = new System.Object[10];

for (int i = 0; i <= 9; i++)

{

   ItemObject[i] = "Item" + i;

}

listBox1.Items.AddRange(ItemObject);

 

ScrollBar

基本定義

ScrollBar是滾動條控件,分成HScrollBar(水平)和VScrollBar(垂直)兩種。有些控件如ListBox,TextBox等可以自動添加滾動條,但是有些控件則需要用程序添加。主要屬性意義為:

Value:滾動條的數值,反映當前移動塊的位置。初始值設定后,運行時停留在這個位置。運行時拉動滾動條,由Scroll事件的e.NewValue參數傳遞過來。

Maximum:Value的最大值,一般為100。

Minimum:Value的最小值,即端點的數值。如果Maximum=100,Minimum=0,LargeChange=10,則從第一個端點開始Value=0,到另一個端點的Value=91。

SmallChange:每次點擊移動的數值,一般為1。

LargeChange:移動塊的長度,一般為10。

和PicturBox控件一起使用

        float vi; //每個單位的移動距離

        float vk=0.8f; //PicturBox顯示高度和實際高度的比例

        int t0,ti; //PicturBox顯示Top和Height。

 

        private void vScrollBar1_Scroll(object sender,System.Windows.Forms.ScrollEventArgs e)

        {   

            this.pictureBox1.Top = t0-Convert.ToInt32(e.NewValue*vi);

            this.pictureBox1.Height = ti+Convert.ToInt32(e.NewValue*vi);

        }  

 

        private void button1_Click(object sender, System.EventArgs e)

        {

            Button   oButton;  

            TextBox   oTextBox;  

            for(int i=1;i<=8;i++)  

            {  

                oButton = new Button();  

                oButton.Text = "按鈕"+ i.ToString();  

                oButton.Location = new System.Drawing.Point(50, i*50);

                oButton.Click += new System.EventHandler(oButton_Click);

                this.pictureBox1.Controls.Add(oButton);

                oTextBox = new TextBox();

                oButton.Tag = oTextBox;

                oTextBox.Text = "1000";

                oTextBox.Location = new System.Drawing.Point(150, i*50);

                this.pictureBox1.Controls.Add(oTextBox);

            }  

        }

 

        private void oButton_Click(object sender, System.EventArgs e)  

        {

            Button btn = (Button)sender;

            TextBox txt = (TextBox)btn.Tag;

            txt.Text = Convert.ToString(Convert.ToInt32(txt.Text) + 1);

        }

 

        private void Form1_Load(object sender, System.EventArgs e)

        {

            vi=vk*pictureBox1.Height/vScrollBar1.Maximum;

            t0=pictureBox1.Top;

            ti=pictureBox1.Height;

        }

 

 

Panel

基本定義

Windows 窗體 Panel(面板)控件用於為其他控件提供可識別的分組。在設計時所有控件均可輕松地移動,當移動 Panel 控件時,它包含的所有控件也將移動。分組在一個面板中的控件可以通過面板的 Controls 屬性進行訪問。

Panel 控件類似於 GroupBox 控件;但只有 Panel 控件可以有滾動條,而且只有 GroupBox 控件顯示標題。

將 AutoScroll 屬性設置為 true,可以自動顯示滾動條。但是這時右邊界和下邊界頂頭,不是太好看。這時需要增加一個不可見的控件或者圖像來調整。

下例在Panel上用程序添加幾個控件,產生滾動效果:

       private void button1_Click(object sender, System.EventArgs e)

        {

            Button oButton;  

            TextBox oTextBox;  

            for(int i=1;i<=8;i++)  

            {  

                oButton = new Button();  

                oButton.Text = "按鈕"+ i.ToString();  

                oButton.Location = new System.Drawing.Point(50, i*50);

                oButton.Click += new System.EventHandler(oButton_Click);

                this.panel1.Controls.Add(oButton);

                oTextBox = new TextBox();

                oButton.Tag = oTextBox;

                oTextBox.Text = "1000";

                oTextBox.Location = new System.Drawing.Point(150, i*50);

                this.panel1.Controls.Add(oTextBox);

            }

            //增加一個不可見按鈕,調整右邊界和下邊界的位置

            oButton = new Button();

            oButton.Location = new System.Drawing.Point(260, 440);

            oButton.Height=0;

            oButton.Width=0;

            this.panel1.Controls.Add(oButton);

        }

 

        private void oButton_Click(object sender, System.EventArgs e)  

        {

            Button btn = (Button)sender;

            TextBox txt = (TextBox)btn.Tag;

            txt.Text = Convert.ToString(Convert.ToInt32(txt.Text) + 1);

        }     

在Panel控件上添加圖像

在Panel控件上不能直接添加圖像。需要在Panel控件上添加一個picturBox,然后把其SizeMode設置為AutoSize(隨着圖像大小調整控件大小)就可以實現圖像的隨意滾動察看。

在Panel控件上畫圖

Panel控件上也可以畫圖。但是滾動時遮蓋的圖像就消失了。這時候需要在Panel控件上添加一個picturBox,然后在picturBox上畫圖,然后用一個LocationChanged事件,每次滾動時重畫一遍即可:

        Pen pen1=new Pen(Color.Green,2);

        Graphics g1;

        void drawLine()

        {

            PointF p1=new PointF(0,0);

            PointF p2=new PointF(100,100);

            g1.DrawLine(pen1,p1,p2);

        }

 

        private void button2_Click(object sender, System.EventArgs e)

        {

            g1=this.pictureBox1.CreateGraphics();

            drawLine();

        }

 

        private void pictureBox1_LocationChanged(object sender, System.EventArgs e)

        {

            drawLine();

        }

 

菜單

普通應用

手工添加即可。可以直接在其上寫各個菜單項的名字,雙擊可以添加程序,使用非常方便。

特殊功能

1.在設計時向菜單項添加選中標記

對於在“菜單設計器”內選定的菜單項(三級菜單以下),單擊該菜單項左側的區域,選中標記√。或者在“屬性”窗口中將 Checked 屬性設置為 True。

以編程方式向菜單項添加選中標記

myMnuItem.Checked = true;

2.在設計時向菜單項添加快捷鍵

在“菜單設計器”內選擇菜單項。在“屬性”窗口中,將 Shortcut 屬性設置為下拉列表中提供的值之一。

以編程方式向菜單項添加快捷鍵

myMnuItem.Shortcut = System.Windows.Forms.Shortcut.F6;

3.向菜單項添加訪問鍵

如鍵入“文件(&F)”,顯示“文件(F)”。

若要定位到此菜單項,請按 ALT 鍵,將焦點移動到菜單欄,然后按該菜單名稱的訪問鍵。當菜單打開並顯示帶訪問鍵的項時,只需按該訪問鍵就可選定該菜單項。或者直接按ALT+主菜單的訪問鍵。

4.將分隔線作為菜單項添加

在菜單設計器中,右擊需要有分隔線的位置,然后選擇“插入分隔符”。或者在設置菜單項的 Text 屬性(在“屬性”窗口中、菜單設計器中或代碼中)時,輸入短划線 (–) 使該菜單項成為分隔線。

其它控件

單選按鈕

單選按鈕是布置一組按鈕,只能選擇一組控件。

本例放置3個單選按鈕,Text屬性分別寫上“已婚”、“未婚”和“離異”,然后添加一個Label控件和一個Button控件,程序如下:

public Form1()

     {

         InitializeComponent();

     label1.Text="請選擇";

……

private void button1_Click(object sender, System.EventArgs e)

         {

              if (radioButton1.Checked == true)

                   label1.Text=radioButton1.Text;

              else if (radioButton2.Checked == true)

                   label1.Text=radioButton2.Text;

              else

                   label1.Text=radioButton3.Text;

     }

}

 

復選框

可以選擇多個的一組控件。

本例放置2個復選按鈕,Text屬性分別寫上“加粗”和“斜體”,然后添加一個Label控件和一個Button控件,程序如下:

private void button1_Click(object sender, System.EventArgs e)

         {

              if (checkBox1.Checked == true)

              {

                   if (checkBox2.Checked == true)

                       label1.Text=checkBox1.Text+checkBox2.Text;

                   else if (checkBox2.Checked == false)

                       label1.Text=checkBox1.Text;

              }

              else

                   if (checkBox2.Checked == true)

                   label1.Text=checkBox2.Text;

              else if (checkBox2.Checked == false)

                   label1.Text="";

     }

 

 

程序產生checkBox

        CheckBox checkBox1=new CheckBox();

 

        void checkSet()

        {

            this.Controls.Add(checkBox1);

            checkBox1.Location = new System.Drawing.Point(50, 64);

            checkBox1.Name = "checkBox1";

            checkBox1.TabIndex = 2;

            checkBox1.Text = "圖層1";

            checkBox1.CheckedChanged += new System.EventHandler(checkBox1_CheckedChanged);

        }

 

        private void button1_Click(object sender, System.EventArgs e)

        {         

            checkSet();

        }

       

        private void checkBox1_CheckedChanged(object sender, System.EventArgs e)

        {

            if (checkBox1.Checked)

                MessageBox.Show("yes");

            else

                MessageBox.Show("no");       

        }

如果要實現標題在左邊,用

                    check1.Width=90;

                    check1.CheckAlign=ContentAlignment.MiddleRight;

要在其它控件顯示:

check3.BringToFront();

 

動態產生控件

以下程序動態動態產生一組Button和TextBox控件,以及點擊Button的事件。

        private void button2_Click(object sender, System.EventArgs e)

        {

            Button   oButton;  

            TextBox   oTextBox;  

            for(int i=1;i<=5;i++)  

            {  

                oButton = new Button();  

                oButton.Text = "按鈕"+ i.ToString();  

                oButton.Location = new System.Drawing.Point(50, i*50);

                oButton.Click += new System.EventHandler(oButton_Click);

                this.Controls.Add(oButton);

                oTextBox = new TextBox();

                oButton.Tag = oTextBox;

                oTextBox.Text = "1000";

                oTextBox.Location = new System.Drawing.Point(150, i*50);

                this.Controls.Add(oTextBox);

            }  

        }

 

        private void oButton_Click(object sender, System.EventArgs e)  

        {

            Button btn = (Button)sender;

            TextBox txt = (TextBox)btn.Tag;

            txt.Text = Convert.ToString(Convert.ToInt32(txt.Text) + 1);

        }

 

Splitter

Windows 窗體 splitter 控件用於在運行時調整停靠控件的大小。Splitter 控件常用於一類窗體,這類窗體上的控件所顯示的數據長度可變,如 Windows 資源管理器,它的數據窗格所包含的信息在不同的時間有不同的寬度。

如果一個控件可由 splitter 控件調整其大小,則當用戶將鼠標指針指向該控件的未停靠的邊緣時,鼠標指針將更改外觀,指示該控件的大小是可以調整的。拆分控件允許用戶調整該控件緊前面的停靠控件的大小。因此,為使用戶能夠在運行時調整停靠控件的大小,請將要調整大小的控件停靠在容器的一條邊緣上,然后將拆分控件停靠在該容器的同一側。

以下例子自動產生幾個控件,可以在運行中調整大小。

        private void CreateMySplitControls()

        {

            TreeView treeView1 = new TreeView();

            ListView listView1 = new ListView();

            Splitter splitter1 = new Splitter();

        

            treeView1.Dock = DockStyle.Left;

            splitter1.Dock = DockStyle.Left;

            splitter1.MinExtra = 100;

            splitter1.MinSize = 75;

            listView1.Dock = DockStyle.Fill;

            treeView1.Nodes.Add("TreeView Node");

            listView1.Items.Add("ListView Item");

            this.Controls.AddRange(new Control[]{listView1, splitter1, treeView1});

        }

 

        private void button1_Click(object sender, System.EventArgs e)

        {

            CreateMySplitControls();

        }

tabControl

Windows 窗體 TabControl 顯示多個選項卡。使用時,先添加一個TabControl控件,把它拉的足夠大。

然后在屬性中添加按鈕。每個按鈕可以控制TabControl的其余頁面,作為一個容器,可以添加其它空間。運行時只要點擊按鈕,就可以切換選項卡,實現不同的功能。

StatusBar

可以向statusBar添加面板(窗格),以分類顯示信息:

        public void CreateStatusBarPanels()

        {

            statusBar1.Panels.Add("");

            statusBar1.Panels.Add("Two");

            statusBar1.Panels.Add("Three");

            statusBar1.Panels[0].Width=200;

            statusBar1.Panels[0].Text="One";

            statusBar1.ShowPanels = true;

        }

 

 

三、字符和字符串

字符串的操作在程序設計中非常有用,因此單獨寫成一章。

Char

基本定義

char 關鍵字用於聲明一個字符。

char 類型的常數可以寫成字符、十六進制換碼序列或 Unicode 表示形式。您也可以顯式轉換整數字符代碼。以下所有語句均聲明了一個 char 變量並用字符 X 將其初始化:

char MyChar = 'X';        // Character literal

char MyChar = '\x0058';   // Hexadecimal

char MyChar = (char)88;   // Cast from integral type

char MyChar = '\u0058';   // Unicode

char 類型可隱式轉換為 ushortintuintlongulongfloatdoubledecimal 類型。但是,不存在從其他類型到 char 類型的隱式轉換。

ToCharArray

將字符串的部分字符復制到 Unicode 字符數組。示例

string str = "012wxyz789";

char[] arr;

arr = str.ToCharArray(3, 4);

顯示:wxyz

計算字符串寬度

由於英文和中文的顯示長度不一樣,所以一些場合要區分。

要引用

using System.Globalization;

程序為:

        //計算一個字符的字符類型,=0漢字,=1英文

        private int getCharType(char ch)

        {

            int i0;           

            UnicodeCategory ca1=new UnicodeCategory();

            ca1=System.Char.GetUnicodeCategory(ch);             

            switch (ca1)

            {

                case UnicodeCategory.OtherPunctuation:

                    i0=0; //漢字

                    break;

                case UnicodeCategory.OtherLetter:

                    i0=0; //漢字

                    break;

                case UnicodeCategory.FinalQuotePunctuation:

                    i0=0; //漢字

                    break;             

                default:                   

                    i0=1; //英文

                    break;

            }

            return i0;

        }

 

        //計算字符串(ss,包含中文)的實際寬度(返回)、起點(x0)和高度(height)

        //輸入字號sz,只對於Pixel單位

        public float StringWidth(string ss,float sz,ref float x0,ref float height)

        {

            char ch1;

            int i,i0=0;

            float width=0;

            float k1=1.02f; //漢字系數

            float k2=0.55f; //英文系數

            float k3=0.15f; //x0系數

            float k4=1.10f; //高度系數

            int i1=0; //漢字個數

            int i2=0; //英文個數

 

            height=k4*sz;

            x0=sz*k3;           

            for(i=0;i<ss.Length;i++)

            {

                ch1=(char)ss[i];

                i0=getCharType(ch1);

                if(i0==0)

                    i1++;

                else

                    i2++;

            }

            width=x0+i1*k1*sz+i2*k2*sz;

            return width;

        }

 

        //返回一個point單位的字體的寬度

        public float PStringWidth(string ss,float sz,ref float x0,ref float height)

        {

            float width=0;

            sz=sz*20/15;

            width=StringWidth(ss,sz,ref x0,ref height);

            return width;

        }

這個方法在sz(字體大小)5~30內比較准確。很大時有誤差。

計算字符串中心

        //根據給定點,找到實際標注點,使得以畫出的字符串以給定點為中心

        PointF StringCenter(string s1,int sz,PointF p0)

        {

            PointF p1=new PointF();

            float x0=0;

            float height=0;

            float width=StringWidth(s1,sz,ref x0,ref height);

            p1.X=p0.X-+x0-width/2;

            p1.Y=p0.Y-height/2;

            return p1;

        }

計算字符串尺寸示例1—畫方框

以下示例利用以上方法,把字符串的長度和高度畫成一個方框。

       private void button2_Click(object sender, System.EventArgs e)

       {

            Graphics g= this.CreateGraphics();

            SolidBrush myBrush=new SolidBrush(Color.Red);

            float x0=0;

            float height=0;

            int sz=10;

            float px=0,py=50;

            PointF p0=new PointF(px,py);

            string s1="我們還34fd還是和平使者";

            Font myFont1 = new Font("宋體",sz,FontStyle.Bold,GraphicsUnit.Pixel);

            float width=StringWidth(s1,sz,ref x0,ref height);           

            g.DrawString(s1, myFont1, myBrush, p0);

            PointF p1=new PointF(px+x0,py);

            PointF p2=new PointF(px+x0+width,py);

            PointF p3=new PointF(px+x0+width,py+height);

            PointF p4=new PointF(px+x0,py+height);

            PointF[] cur ={p1,p2,p3,p4};

            Pen pen1=new Pen(Color.Blue,2);

            g.DrawPolygon(pen1,cur);

       }

計算字符串尺寸示例2—找中點

       private void button1_Click(object sender, System.EventArgs e)

       {

            Graphics g= this.CreateGraphics();

            SolidBrush myBrush=new SolidBrush(Color.Red);

            PointF ps=new PointF();

            int sz=10;            

            PointF p0=new PointF(300,100);

            string s1="我們還34fd還是和平使者";

            Font myFont1 = new Font("宋體",sz,FontStyle.Bold,GraphicsUnit.Pixel);

            ps=StringCenter(s1,sz,p0);

            g.DrawString(s1, myFont1, myBrush, ps);

            //以下畫十字線表示中心位置

            PointF p1=new PointF(0,p0.Y);

            PointF p2=new PointF(600,p0.Y);

            PointF p3=new PointF(p0.X,0);

            PointF p4=new PointF(p0.X,300);

            Pen pen1=new Pen(Color.Blue,1);

            g.DrawLine(pen1,p1,p2);

            g.DrawLine(pen1,p3,p4);

       }

 

分行操作

回車符和換行符

“\r\n”

顯示換行的語句為:

textBox1.Text="ok\r\n";

     textBox1.Text+="ok1";

字符串分行

string myString1 = "This is the first line of my string.\n" +

      "This is the second line of my string.\n" +

      "This is the third line of the string.\n";

string myString2 = @"This is the first line of my string.

This is the second line of my string.

This is the third line of the string.";

字符串操作

字符串表示

用@后邊的字符串不被處理。

A1=@"c:\Docs\Source\a.txt";

string s1=@"c=""a.txt"; //顯示:c=”a.txt

string s1=@"c=""a.txt"""; //顯示:c=”a.txt”

If (s1 == @"""") Then  //s1=""

 

求字符串長度

string s1="fdkls我們";

         string s2=Convert.ToString(s1.Length);

     MessageBox.Show(s2);

運行顯示為7,所有字符個數。

裁剪字符串

String s = "123abc456";

Console.WriteLine(s.Remove(3, 3));

打印“123456”。

Split方法

標識此實例中的子字符串(它們由數組中指定的一個或多個字符進行分隔),然后將這些子字符串放入一個 String 數組中。

簡單的例子

可以按照“,”分開,也可以去除空格。

         private void button1_Click(object sender, System.EventArgs e)

         {            

              string astring="123,456 78,789";

              string [] split;

              Char [] chr=new Char [] {',',' '};

              split = astring.Split(chr);

              MessageBox.Show("/"+split[0]+"/");

     }

這時可以分成123,456,78,789四個字符串。

注意,前后空白也可以看成是一個字符串,要消除,用

astring=astring.Trim();

就可以了。

復雜的例子

當存在兩個空格時,就出現找出空字符串的錯誤。用以下方法可以去掉空的字符串:

         string [] Split0(string [] sp)

         {

              string [] sp1=new string [sp.Length];

              int i=0,j=0;

              foreach (string s1 in sp)

              {

                   if (s1!="")

                   {                     

                       sp1[i]=s1;

                       i=i+1;

                   }

              }            

              string [] sp2=new string [i];

              for (j=0;j<i;j++) 

                   sp2[j]=sp1[j];             

              return sp2;

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {            

              string astring=" 123,456   78,789  ";

              string [] split;

              Char [] chr=new Char [] {',',' '};

              split = astring.Split(chr);

              split =Split0(split);

              MessageBox.Show("/"+split[0]+"/");

     }

 

 

五、文件操作

文件操作

刪除

以下均為在控制台應用程序中使用的程序。開始要進行以下三個引用:

using System;

using System.IO;

using System.Text;

程序如下:

class Test

{

     public static void Main()

     {

         string path = @"d:\chen\MyTest.txt";

         if (File.Exists(path))

         {

              File.Delete(path);

     }

     }

}

如果采用相對路徑,用

string sfile = Directory.GetCurrentDirectory() + @"\F8.txt";

對於在一個.net項目中,默認的路徑是在\bin\debug中,如果要放在項目文件目錄中,用

string sfile = Directory.GetCurrentDirectory() + @"\..\..\F8.txt";

生成新文件

可以用:

File.Create(path);

或者

FileStream fs = File.Create(path);

復制

File.Copy(path,path1,true);

如果最后用false,則第二個文件有時,發生錯誤。

讀寫文本文件

using System;

using System.IO;

 

private void button1_Click(object sender, System.EventArgs e)

         {

              string s1 = @"D:\chen\mytest.txt";

              string s2 = @"D:\chen\mytest1.txt";

              String input;

 

              if (!File.Exists(s1))

              {

                   MessageBox.Show("File does not exist.");

                   return;

              }

 

              StreamReader sr = File.OpenText(s1);

              StreamWriter wr = new StreamWriter(s2);

 

              while ((input=sr.ReadLine())!=null)

              {

                   wr.WriteLine(input);

              }

              MessageBox.Show("The end.");

              sr.Close();

              wr.Close();

         }

讀寫中文

              string s1 = @"d:\chen\a1.txt";           

              StreamReader sr = new StreamReader(s1,Encoding.GetEncoding("gb2312"));

              string rl;

              while((rl=sr.ReadLine())!=null)

              {

                   MessageBox.Show(rl);

              }

          sr.Close();

 

文件操作控件

打開文件

用openFileDialog控件。

         private void button1_Click(object sender, System.EventArgs e)

         {  

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory=Directory.GetCurrentDirectory();

            openFileDialog1.Filter = "Cursor Files|*.cur";

            openFileDialog1.Title = "Select a Cursor File";      

          

            if(openFileDialog1.ShowDialog() == DialogResult.OK)

            {

                System.IO.StreamReader sr = new

                    System.IO.StreamReader(openFileDialog1.FileName);

                MessageBox.Show(sr.ReadToEnd());

                sr.Close();

            }          

     }

選擇文件夾

在工具箱上選擇folderBrowserDialog:

            folderBrowserDialog1.ShowDialog();          

            string s1 = folderBrowserDialog1.SelectedPath.ToString()+@"\mytest.txt";

        StreamWriter wr = new StreamWriter(s1);

 

 

 

 

六、繪圖

基本繪圖

畫直線

在Button1中加入以下程序:

System.Drawing.Pen myPen;

     myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

     System.Drawing.Graphics formGraphics = this.CreateGraphics();

     formGraphics.DrawLine(myPen, 0, 0, 200, 200);

     myPen.Dispose();

formGraphics.Dispose();

就可以在Form1上面畫一條線了。用

     myPen = new System.Drawing.Pen(System.Drawing.Color.Red,3);

可以改變線的寬度。

最簡單的畫線程序

            Pen pen1=new Pen(Color.Green,2);

            Graphics g1=this.CreateGraphics();

            PointF p1=new PointF(0,0);

            PointF p2=new PointF(100,100);

            g1.DrawLine(pen1,p1,p2);

            pen1.Dispose();

            g1.Dispose();

最后兩句可以不寫,程序關閉時自動完成。

畫橢圓

     System.Drawing.Pen myPen;

     myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

     System.Drawing.Graphics formGraphics = this.CreateGraphics();

     formGraphics.DrawEllipse(myPen, new Rectangle(0,0,200,300));

     myPen.Dispose();

formGraphics.Dispose();

以下畫一個橢圓並填充。

System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);

System.Drawing.Graphics formGraphics = this.CreateGraphics();

formGraphics.FillEllipse(myBrush, new Rectangle(0,0,200,300));

myBrush.Dispose();

formGraphics.Dispose();

以橢圓的中心點畫圖

        //以給定點找畫橢圓的原始點,使得橢圓的中心點是給定點

        PointF EllipseCenter(int xs,int ys,PointF p0)

        {

            float ek=0.5f;           

            PointF p1=new PointF();

            p1.X=p0.X-xs*ek;

            p1.Y=p0.Y-ys*ek;

            return p1;

        }

 

       private void button1_Click(object sender, System.EventArgs e)

       {

            Graphics g= this.CreateGraphics();

            Pen pen1=new Pen(Color.Yellow,1);

            Pen pen2=new Pen(Color.Red,1);

            PointF ps=new PointF();

            int xs=1,ys=1;  //半軸     

            PointF p0=new PointF(300,100);           

            ps=EllipseCenter(xs,ys,p0);

           

            //以下畫十字線表示中心位置

            PointF p1=new PointF(0,p0.Y);

            PointF p2=new PointF(600,p0.Y);

            PointF p3=new PointF(p0.X,0);

            PointF p4=new PointF(p0.X,300);           

            g.DrawLine(pen1,p1,p2);

            g.DrawLine(pen1,p3,p4);

            g.DrawEllipse(pen2,ps.X,ps.Y,xs,ys);

       }

 

點弧線

     System.Drawing.Pen myPen;

     myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

     System.Drawing.Graphics formGraphics = this.CreateGraphics();

     formGraphics.DrawArc(myPen, 100, 50, 140, 70, 30, 180);

     myPen.Dispose();

     formGraphics.Dispose();

多點直線

System.Drawing.Pen myPen;

              myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

              System.Drawing.Graphics formGraphics = this.CreateGraphics();

 

              PointF point1 = new PointF( 50.0F,  50.0F);

              PointF point2 = new PointF(100.0F,  25.0F);

              PointF point3 = new PointF(200.0F, 5.0F);

              PointF point4 = new PointF(250.0F,  50.0F);

              PointF point5 = new PointF(300.0F, 100.0F);

              PointF point6 = new PointF(350.0F, 200.0F);

              PointF point7 = new PointF(250.0F, 250.0F);

              PointF[] curvePoints =

              {

                   point1,

                   point2,

                   point3,

                   point4,

                   point5,

                   point6,

                   point7

              };

 

              formGraphics.DrawLines(myPen, curvePoints);

              myPen.Dispose();

          formGraphics.Dispose();

 

也可以用以下方式給數組賦值:

PointF[] pt=new PointF[]{new PointF(2,2),new PointF(25,150),new PointF(100,100)};

多點弧線

數據同上,修改如下:

int offset = 1; //開始點(從0開始)

              int numSegments = 5; //包含后續點數

              float tension = 1.0F;

          formGraphics.DrawCurve(myPen, curvePoints, offset, numSegments, tension);

 

以下程序可以畫一個封閉曲線:

private void button1_Click(object sender, System.EventArgs e)

         {

              System.Drawing.Pen myPen;

              myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

              System.Drawing.Graphics formGraphics = this.CreateGraphics();

              PointF point1 = new PointF( 50.0F,  50.0F);

              PointF point2 = new PointF(100.0F,  25.0F);

              PointF point3 = new PointF(200.0F, 5.0F);

              PointF point4 = new PointF(250.0F,  50.0F);

              PointF point5 = new PointF(300.0F, 100.0F);

              PointF point6 = new PointF(350.0F, 200.0F);

              PointF point7 = new PointF(250.0F, 250.0F);

              PointF point8 = new PointF(40.0F, 150.0F);

              PointF[] curvePoints =

              {

                   point1,

                   point2,

                   point3,

                   point4,

                   point5,

                   point6,

                   point7,

                   point8,

                   point1

              };

              int offset = 0;

              int numSegments = 8;

              float tension = 1.0F;

              formGraphics.DrawCurve(myPen, curvePoints, offset, numSegments, tension);

//            formGraphics.DrawLines(myPen, curvePoints);

              myPen.Dispose();

              formGraphics.Dispose();

     }

 

如果是任意3點(或多點),在起始點不容易圓滑。可以用以下方法畫封閉曲線:

PointF[] curvePoints =

              {

                   point3,

                   point1,

                   point2,

                   point3,

                   point1

              };

              int offset = 1;

              int numSegments = 3;

          float tension = 0.5F;

 

這樣可以保證第一個點處比較圓滑。

參數設置

設置線段寬度:

myPen.Width =3;

在pictrueBox上面畫線,修改this:

System.Drawing.Graphics formGraphics = picBox1.CreateGraphics();

填充

              System.Drawing.SolidBrush myBrush = new ystem.Drawing.SolidBrush(System.Drawing.Color.LightPink);

              System.Drawing.Pen myPen;

              myPen = new System.Drawing.Pen(System.Drawing.Color.Red,1);

              System.Drawing.Graphics formGraphics = pictureBox1.CreateGraphics();

              PointF point1 = new PointF( 50.0F,  50.0F);

              PointF point2 = new PointF(100.0F,  25.0F);

              PointF point3 = new PointF(200.0F, 5.0F);

              PointF point4 = new PointF(250.0F,  50.0F);

              PointF point5 = new PointF(300.0F, 100.0F);

              PointF point6 = new PointF(350.0F, 200.0F);

              PointF point7 = new PointF(250.0F, 250.0F);

              PointF[] curvePoints =

              {

                   point1,

                   point2,

                   point3,

                   point4,

                   point5,

                   point6,

                   point7

              };

              formGraphics.FillPolygon(myBrush,curvePoints);

              formGraphics.DrawPolygon(myPen,curvePoints);

              myPen.Dispose();

              myBrush.Dispose();

          formGraphics.Dispose();

顏色

顏色基本設置

普通顏色設置可以直接選取系統定義的顏色。高級設置采用RGB顏色。

Color myColor;

myColor = Color.FromArgb(23,56,78);

每個數字均必須是從 0 到 255 之間的一個整數,分別表示紅、綠、藍三種原色。其中 0 表示沒有該顏色,而 255 則為所指定顏色的完整飽和度。如Color.FromArgb(0,255,0)表示綠色,Color.FromArgb(255,255,0)表示黃色,Color.FromArgb(0,0,0) 呈現為黑色,而 Color.FromArgb(255,255,255) 呈現為白色。

還可以設置透明度,如

Color myColor;

myColor = Color.FromArgb(127, 23, 56, 78);

127表示50%的透明度,255表示完全不透明。

選擇顏色

以下程序可以從調色板選擇一個顏色,在textBox上面顯示。

        private void button1_Click(object sender, System.EventArgs e)

        {

            ColorDialog MyDialog = new ColorDialog();

            MyDialog.AllowFullOpen = false ;

            MyDialog.ShowHelp = true ;

            MyDialog.Color = textBox1.ForeColor ;

   

            if (MyDialog.ShowDialog() == DialogResult.OK)

                textBox1.ForeColor =  MyDialog.Color;

     }

產生窗體選擇顏色

本程序在一個菜單里調用選擇程序,產生一個動態的窗體,選擇顏色后返回主程序,刷新原來的頁面。

由於沒有掌握控制動態控件集合的方法,只好用枚舉的方法定義動態控件,對於多於10個的顏色序列,需要修改程序。

        Form form1;

        bool Cform=true;

        //顏色設置

        private void menuItem31_Click(object sender, System.EventArgs e)

        {

            while (Cform)

            {

                CreateColorForm();

                Tuli1();

                DisLine();

            }

            Cform=true;

        }

 

        //產生顏色輸入窗體

        private void CreateColorForm()

        {

            int i;            

            form1=new Form();

                    

            Button [] ColorButton  = new Button [myPloys.marks1.Count];

            Label [] ColorLabel  = new Label [myPloys.marks1.Count];

            Button button0 = new Button ();

                     

            form1.Width=130;

            form1.Height=130+myPloys.marks1.Count*30;

            form1.Text = "等值線顏色輸入";        

            form1.FormBorderStyle = FormBorderStyle.FixedDialog;

            form1.ControlBox = false;

            form1.StartPosition = FormStartPosition.CenterScreen;

                     

            button0.Text = "退出";

            button0.Width=80;

            button0.Location=new Point(25,50+myPloys.marks1.Count*30);

            form1.Controls.Add(button0);

            form1.CancelButton = button0;  

 

            for (i=0;i<myPloys.marks1.Count;i++)  

            {              

                ColorLabel[i]=new Label();               

                ColorLabel[i].Location=(Point)new Point(30,30+30*i);

                ColorLabel[i].Width=30;

                ColorLabel[i].Text=myPloys.marks1[i].ToString();

                form1.Controls.Add(ColorLabel[i]);

 

                ColorButton[i]=new Button();

                ColorButton[i].BackColor=cColor[i];

                ColorButton[i].Location=(Point)new Point(60,26+30*i);

                ColorButton[i].Width=30;

                switch (i)

                {

                    case 0:

                        ColorButton[i].Click += new System.EventHandler(ColorButton0_Click);

                        break;

                    case 1:

                        ColorButton[i].Click += new System.EventHandler(ColorButton1_Click);

                        break;

                    case 2:

                        ColorButton[i].Click += new System.EventHandler(ColorButton2_Click);

                        break;

                    case 3:

                        ColorButton[i].Click += new System.EventHandler(ColorButton3_Click);

                        break;

                    case 4:

                        ColorButton[i].Click += new System.EventHandler(ColorButton4_Click);

                        break;

                    case 5:

                        ColorButton[i].Click += new System.EventHandler(ColorButton5_Click);

                        break;

                    case 6:

                        ColorButton[i].Click += new System.EventHandler(ColorButton6_Click);

                        break;

                    case 7:

                        ColorButton[i].Click += new System.EventHandler(ColorButton7_Click);

                        break;

                    case 8:

                        ColorButton[i].Click += new System.EventHandler(ColorButton8_Click);

                        break;

                    case 9:

                        ColorButton[i].Click += new System.EventHandler(ColorButton9_Click);

                        break;

                    case 10:

                        ColorButton[i].Click += new System.EventHandler(ColorButton10_Click);

                        break;

                    default:                       

                        break;

                }               

                form1.Controls.Add(ColorButton[i]);

            }          

             button0.Click += new System.EventHandler(button0_Click);

            form1.ShowDialog(); 

        }

 

        private void ColorSelect(int si)

        {

            ColorDialog MyDialog = new ColorDialog();

            MyDialog.AllowFullOpen = true ;

            MyDialog.ShowHelp = true ;     

            MyDialog.Color = cColor[si] ;   

            if (MyDialog.ShowDialog() == DialogResult.OK)

                cColor[si] =  MyDialog.Color;

            form1.Dispose();

        }

        

        private void ColorButton0_Click(object sender, System.EventArgs e)

        {  ColorSelect(0);  }

        private void ColorButton1_Click(object sender, System.EventArgs e)

        {  ColorSelect(1);  }

        private void ColorButton2_Click(object sender, System.EventArgs e)

        {  ColorSelect(2);  }

        private void ColorButton3_Click(object sender, System.EventArgs e)

        {  ColorSelect(3);  }

        private void ColorButton4_Click(object sender, System.EventArgs e)

        {  ColorSelect(4);  }

        private void ColorButton5_Click(object sender, System.EventArgs e)

        {  ColorSelect(5);  }

        private void ColorButton6_Click(object sender, System.EventArgs e)

        {  ColorSelect(6);  }

        private void ColorButton7_Click(object sender, System.EventArgs e)

        {  ColorSelect(7);  }

        private void ColorButton8_Click(object sender, System.EventArgs e)

        {  ColorSelect(8);  }

        private void ColorButton9_Click(object sender, System.EventArgs e)

        {  ColorSelect(9);  }

        private void ColorButton10_Click(object sender, System.EventArgs e)

        {  ColorSelect(10);  }

       

        private void button0_Click(object sender, System.EventArgs e)

        {

            Cform=false;

            form1.Dispose();          

        }

 

 

Font和標注

基本操作

可以在指定的點開始寫字,也可以在一個范圍(如矩形)內寫字。

         Font myFont = new Font("Times New Roman", 14);

         Graphics g = this.CreateGraphics();

         Pen myPen=new Pen(Color.Black);

         System.Drawing.SolidBrush myBrush=new SolidBrush(Color.Red);

         g.DrawRectangle(myPen,10, 10, 100, 200);

         g.DrawString("Look at this text!", myFont, myBrush, new RectangleF(10, 10, 100, 200));

         g.DrawString("Look at this text!", myFont, myBrush, 10, 250);

畫點和標注

     System.Drawing.Pen myPen;

     myPen = new System.Drawing.Pen(System.Drawing.Color.Red,1);

     System.Drawing.Graphics formGraphics = this.CreateGraphics();

     System.Drawing.SolidBrush drawBrush = new      System.Drawing.SolidBrush(System.Drawing.Color.Black);

     System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 8);

     string drawString = "201";

     float x = 100.0f;

     float y = 100.0f;

     formGraphics.DrawEllipse(myPen, x, y,4,4);                           

     formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);           

 

     myPen.Dispose();

     drawFont.Dispose();

     drawBrush.Dispose();

formGraphics.Dispose();

 

Font定義

public Font(

   FontFamily family,

   float emSize,

   FontStyle style,

   GraphicsUnit unit

);

以下的例子可以改變字體,大小、字形、單位,還可以設置成垂直。

//    Font myFont = new Font("Times New Roman",14,FontStyle.Italic,GraphicsUnit.Millimeter);

            Font myFont = new Font("隸書",34,FontStyle.Underline,GraphicsUnit.Pixel);   

            Graphics g = this.CreateGraphics();

            System.Drawing.SolidBrush myBrush=new SolidBrush(Color.Red);

            System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat (StringFormatFlags.DirectionVertical);

            g.DrawString("Hello!你好", myFont, myBrush, 10, 10,drawFormat);

根據給定點找到實際標注點

        //根據給定點,找到實際標注點,使得以畫出的字符串以給定點為中心

        public PointF StringCenter(string s1,float sz,PointF p0)

        {

            PointF p1=new PointF();

            float x0=0;

            float height=0;

            float width=StringWidth(s1,sz,ref x0,ref height);

            p1.X=p0.X-+x0-width/2;

            p1.Y=p0.Y-height/2;

            return p1;

        }

 

pictureBox

用pictureBox畫圖

和在form上面畫圖類似,只是把this替換成pictureBox1:

              System.Drawing.Pen myPen;

              myPen = new System.Drawing.Pen(System.Drawing.Color.Red,1);

              System.Drawing.Graphics formGraphics = pictureBox1.CreateGraphics();

              System.Drawing.SolidBrush drawBrush = new

              System.Drawing.SolidBrush(System.Drawing.Color.Black);

              System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 8);

              string drawString = "201";

              float x = 200.0f;

              float y = 100.0f;

              formGraphics.DrawEllipse(myPen, x, y,4,4);                           

              formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);           

 

              myPen.Dispose();

              drawFont.Dispose();

              drawBrush.Dispose();

          formGraphics.Dispose();

用pictureBox顯示一個圖片

有固定模式和縮放模式,通過設置SizeMode實現。程序如下:

              pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //按圖像文件大小縮放

//            pictureBox1.Image = Image.FromFile ("abc.bmp");  //文件放在\bin\Debug文件夾

          pictureBox1.Image = Image.FromFile (@"..\..\abc1.bmp");  //文件放在程序文件夾

Region

基本概念

指示由矩形和由路徑構成的圖形形狀的內部。

基本操作

         System.Drawing.Graphics e = this.CreateGraphics();

         Rectangle regionRect = new Rectangle(20, 20, 100, 100);

         e.DrawRectangle(Pens.Black, regionRect);          

         RectangleF complementRect = new RectangleF(90, 30, 100, 100);

         e.DrawRectangle(Pens.Red,Rectangle.Round(complementRect));

    

         Region myRegion = new Region(regionRect);         

         myRegion.Intersect(complementRect);

        

         SolidBrush myBrush = new SolidBrush(Color.Blue);

     e.FillRegion(myBrush, myRegion);

主要圖形操作還有Union和Xor。

Polygon的鏤空

采用異或(Xor)運算。需要把polygon轉換成路徑:

            Graphics g1 = this.CreateGraphics();

            GraphicsPath myPath1=new GraphicsPath();

            PointF[] pts=new PointF[]{new PointF(2,20),new PointF(250,0)

              ,new PointF(100,100),new PointF(90,150),new PointF(10,70)};

            myPath1.AddPolygon(pts);

            g1.DrawPath(Pens.Black,myPath1);

 

            GraphicsPath myPath2=new GraphicsPath();

            PointF[] pts1=new PointF[]{new PointF(20,30),new PointF(50,70)

              ,new PointF(100,40)};

            myPath2.AddPolygon(pts1);

            g1.DrawPath(Pens.Black,myPath2);

          

            Region myRegion = new Region(myPath1);

            myRegion.Xor(myPath2);    

            SolidBrush myBrush = new SolidBrush(Color.Blue);

            g1.FillRegion(myBrush, myRegion);

 

如果要鏤空多個空洞,需要把這些空洞都加入到myPath2中,其余操作同樣。

采用交、並和異或運算,都可以把兩個對象互換。

顯示數據

         public void DisplayRegionData(Graphics e, int len,RegionData dat)

         {

              int i;

              float x = 20, y = 140;

              Font myFont = new Font("Arial", 8);

              SolidBrush myBrush = new SolidBrush(Color.Black);

              e.DrawString("myRegionData = ",myFont,    myBrush,new PointF(x, y));

              y = 160;

              for(i = 0; i < len; i++)

              {

                   if(x > 300)

                   {

                       y += 20;

                       x = 20;

                   }

                   e.DrawString(dat.Data[i].ToString(),myFont,    myBrush,new PointF(x, y));

                   x += 30;

              }

     }

 

路徑

基本應用

用GraphicsPath可以把各種繪圖元素(包括文字)包含進來,最后用DrawPath畫出來。

需要:using System.Drawing.Drawing2D;

         private void button2_Click(object sender, System.EventArgs e)

         {

              Pen myPen = new Pen(System.Drawing.Color.Red,1);

              System.Drawing.Graphics formGraphics = this.CreateGraphics();

              GraphicsPath myPath1=new GraphicsPath();

             

            myPath1.AddLine(0, 0, 10, 20);

            myPath1.AddEllipse(20,20,10,10);

            myPath1.AddLine(40, 40, 50, 120);

 

            formGraphics.DrawPath(myPen, myPath1);

            myPath1.Dispose();

              myPen.Dispose();

              formGraphics.Dispose();

     }

不連續線條

用一個半徑為0的點加在中間:

            myPath1.AddLine(0, 0, 10, 20);

            myPath1.AddEllipse(20,20,0,0);

            myPath1.AddLine(40, 40, 50, 120);

也可以用兩個path,然后用

path2.AddPath(path3,false);

復雜應用

路徑可以包含其它路徑,匯總成一個大的圖形。

還可以通過矩陣變換進行縮放、平移和旋轉。

簡單Matrix變換

可以通過矩陣變換進行圖形的變換。

         private void button1_Click(object sender, System.EventArgs e)

         {           

            System.Drawing.Graphics e1 = this.CreateGraphics();

            Pen myPen = new Pen(Color.Blue, 1);

            Pen myPen2 = new Pen(Color.Red, 1);

 

            Matrix myMatrix1 = new Matrix(1.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f);  // x和y方向都放大3倍

//            Matrix myMatrix1 = new Matrix(1.0f, 0.0f, 0.0f, 1.0f, 50.0f, 50.0f);  // 平移50,50

            e1.DrawRectangle(myPen, 0, 0, 100, 100);

            e1.Transform = myMatrix1;

            e1.DrawRectangle(myPen2, 0, 0, 100, 100);

 

            myPen.Dispose();

            e1.Dispose();    

     }

復雜Matrix變換

下例顯示縮放、旋轉和移動變換。

        public void MultiplyExample(PaintEventArgs e)

        {

            Pen myPen = new Pen(Color.Blue, 2);

            Pen myPen2 = new Pen(Color.Red, 1);

            Matrix myMatrix1 = new Matrix(3.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f);  // Scale

            Matrix myMatrix2 = new Matrix(0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f); // Rotate 90,

            Matrix myMatrix3 = new Matrix(1.0f, 0.0f, 0.0f, 1.0f, 250.0f, 50.0f);  // Translate

 

            ListMatrixElements(e, myMatrix1, "Beginning Matrix", 6, 40);

            myMatrix1.Multiply(myMatrix2, MatrixOrder.Append);

            ListMatrixElements(e,myMatrix1,"Matrix After 1st Multiplication",6,60);

            myMatrix1.Multiply(myMatrix3, MatrixOrder.Append);

            ListMatrixElements(e, myMatrix1,"Matrix After 2nd Multiplication",6,80);

 

            e.Graphics.DrawRectangle(myPen, 0, 0, 100, 100);

            e.Graphics.Transform = myMatrix1;

            e.Graphics.DrawRectangle(myPen2, 0, 0, 100, 100);

        }

 

        public void ListMatrixElements(PaintEventArgs e,Matrix matrix,string matrixName,

            int numElements,int y)

        {         

            int i;

            float x = 20, X = 200;

            Font myFont = new Font("Arial", 8);

            SolidBrush myBrush = new SolidBrush(Color.Black);

            e.Graphics.DrawString(matrixName + ":  ", myFont,myBrush,x,y);

            for(i=0; i<numElements; i++)

            {

                e.Graphics.DrawString(matrix.Elements[i].ToString() + ", ",myFont,myBrush,X,y);

                X += 30;

            }

      }

解決放大線條變寬問題

放大后的線條全部變寬,無法應用於GIS變換。對於多個線條組成的圖形需要縮放和平移時,可以重新生成一個點集(其中自己加上縮放和平移計算)來做。

從路徑轉換到點集用PathPoints屬性。

 

Image

簡單保存

可以利用Image類的Save方法保存目前顯示的文件。需要在Form中定義:

     public class Form1 : System.Windows.Forms.Form

     {

         private System.Windows.Forms.Button button1;

         private System.Windows.Forms.Button button2;

         private System.Windows.Forms.PictureBox pictureBox1;

     private Image cuurimage;

然后在程序中引用即可。

              cuurimage=pictureBox1.Image;

          cuurimage.Save("abc2.bmp");

利用動態Image畫圖

 

              PointF p1 = new PointF();

              PointF p2 = new PointF();

             

              Pen myPen = new Pen(Color.Black,1);           

              cuurimage = Image.FromFile("abc.bmp");

              Graphics g = Graphics.FromImage(cuurimage);

              Color [] c ={Color.LightPink,Color.Red,Color.Blue,Color.Brown,Color.Black};   

              for(k=0;k<=LineColor.Count-1;k++)

              {

                   myPen.Color = c[(int)LineColor[k]];               

                   p1=(PointF)LineArray[i];

                   i++;

                   p2=(PointF)LineArray[i];

                   i++;

                   g.DrawLine(myPen,p1,p2);

              }

 

              myPen.Dispose();

              g = CreateGraphics();

              g.DrawImage(cuurimage,50,0,cuurimage.Width+100,cuurimage.Height+10);

          g.Dispose();

畫圖保存

在一個pictureBox上保存所畫圖像。

先需要加載一個背景圖片,把圖畫在這個圖片上,最后保存到另外一個文件中。

     private Image cuurimage;

         private void button2_Click(object sender, System.EventArgs e)

         {

              Pen myPen = new Pen(System.Drawing.Color.Red,2);

            pictureBox1.Image = Image.FromFile (@"..\..\abc1.bmp");

            cuurimage = pictureBox1.Image;

            Graphics g = Graphics.FromImage(cuurimage);         

              g.DrawEllipse(myPen, 100, 100,44,14);         

            cuurimage.Save("abc0.bmp");

              myPen.Dispose();           

              g.Dispose();

     }

利用Image擦除圖像

下例要先准備一個jpg圖像文件。

先把jpg文件放在pictureBox的Graphics類g1上,然后在其上畫圖,保存在一個image類的變量中。需要擦除的圖形畫在另外一個Graphics類g2上,然后在g1上用DrawImage方法,就可以把g2上的圖形全部擦除。

注意,中間不能有任何Refresh方法。擦除時才能使用一次Refresh方法。

        Image imgBack;

        System.Drawing.Graphics g1,g2;

        Pen Pen1;

       //新圖形

        private void button1_Click(object sender, System.EventArgs e)

        {

            g2 = pictureBox1.CreateGraphics();

            Pen1=new Pen(Color.Red,2);  

            g2.DrawLine(Pen1,10,10,200,200);

//            pictureBox1.Refresh();

        }

        //原始圖形

        private void button2_Click(object sender, System.EventArgs e)

        {            

            pictureBox1.Image = Image.FromFile (@"s4.jpg");

            imgBack=pictureBox1.Image;

            g1 = Graphics.FromImage(pictureBox1.Image);

            Pen1=new Pen(Color.Blue,2);  

            g1.DrawLine(Pen1,10,100,200,20);

//            pictureBox1.Refresh();

        }

        //擦除

        private void button3_Click(object sender, System.EventArgs e)

        {

            g1.DrawImage(imgBack,0,0);

            pictureBox1.Refresh();

        }

 

圖形其它

找到一個點

以下程序可以找到一個存在的點,並在鼠標移動時改變光標和提示。點擊顯示其它信息。

        PointF Pt1=new PointF();

        PointF Pt2=new PointF();

        System.Drawing.Graphics g;

        int kk1=0; //判斷是否重畫,=1為已經重畫

        int kk2=0; //判斷在距離內,=1為在距離內

        double jl0=5; //距離

        

        private static float Distance(PointF p1,PointF p2)

        {

            return (float)Math.Sqrt((p1.X-p2.X)*(p1.X-p2.X)+(p1.Y-p2.Y)*(p1.Y-p2.Y));

        }    

 

        private void Form1_Closed(object sender, System.EventArgs e)

        {

            g.Dispose();

        }

 

        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

        {             

            if (kk2==1)

                MessageBox.Show("xianshi");   

        }

 

        private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            double jl1;

            Pt2.X=e.X;

            Pt2.Y=e.Y;          

            jl1=Distance(Pt1,Pt2);

            if (jl1<jl0)

            {

                this.Cursor=Cursors.Hand;

                label1.Show();

                label1.Left=(int)Pt1.X-6;

                label1.Top=(int)Pt1.Y-20;

                label1.Text="x="+Pt1.X.ToString()+" y="+Pt1.Y.ToString();

                label1.Width=label1.Text.Length*7;

                label1.Height=15;

                kk2=1; //找到圖像

                kk1=0; //沒有顯示圖像

            }

            else

            {

                if (kk1==0)

                {

                    this.Cursor=Cursors.Arrow;

                    kk2=0;

                    label1.Hide();

                    g.FillEllipse(new SolidBrush(Color.Black),Pt1.X,Pt1.Y,5,5); //重新顯示

                    kk1=1;

                }

            }

        }

        

        private void button2_Click(object sender, System.EventArgs e)

        {

            Pt1.X=100;

            Pt1.Y=100;              

            g.FillEllipse(new SolidBrush(Color.Black),Pt1.X,Pt1.Y,5,5);                 

        }

 

        private void Form1_Load(object sender, System.EventArgs e)

        {

            g = this.CreateGraphics();   

            label1.Hide();

        }

 

 

拖動一個點

可以實現發現點時改變鼠標光標和顯示坐標提示,拖動鼠標完成點的移動。

在form上放置一個button1和label1,程序如下:

         PointF Pt1=new PointF();

         PointF Pt2=new PointF();

         System.Drawing.Graphics g;

         int kk1=0; //判斷是否拖動,=1為拖動

         int kk2=0; //判斷在距離內,=1為在距離內

         double jl0=5; //距離

        

         private static float Distance(PointF p1,PointF p2)

         {

              return (float)Math.Sqrt((p1.X-p2.X)*(p1.X-p2.X)+(p1.Y-p2.Y)*(p1.Y-p2.Y));

         }       

 

         private void Form1_Closed(object sender, System.EventArgs e)

         {

              g.Dispose();

         }

 

         private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)

         {

              if (kk1==1 & kk2==1)

              {

                   Pt2.X=e.X;

                   Pt2.Y=e.Y;   

                   g.FillEllipse(new SolidBrush(this.BackColor),Pt1.X,Pt1.Y,5,5);   //刪除原來的點

                   g.FillEllipse(new SolidBrush(Color.Black),Pt2.X,Pt2.Y,5,5);      //畫新的點

                   Pt1=Pt2;

                   this.Cursor=Cursors.Arrow;

                   kk1=0;

                   kk2=0;

                   label1.Hide();

              }

              this.Cursor=Cursors.Arrow;

         }

 

         private void Form1_Load(object sender, System.EventArgs e)

         {

              g = this.CreateGraphics(); 

              label1.Hide();

         }

 

         private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

         {                 

              if (kk2==1)

                   kk1=1;  

              else

                   kk1=0;                

         }

 

         private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)

         {

              double jl1;

              Pt2.X=e.X;

              Pt2.Y=e.Y;            

              jl1=Distance(Pt1,Pt2);

              if (jl1<jl0)

              {

                   this.Cursor=Cursors.Hand;

                   label1.Show();

                   label1.Left=(int)Pt2.X-6;

                   label1.Top=(int)Pt2.Y-20;

                   label1.Text="x="+Pt1.X.ToString()+" y="+Pt1.Y.ToString();

                   kk2=1;

              }

              else if (kk1==0)

              {

                   this.Cursor=Cursors.Arrow;

                   kk2=0;

                   label1.Hide();

              }

         }

        

         private void button1_Click(object sender, System.EventArgs e)

         {

              Pt1.X=100;

              Pt1.Y=100;                 

              g.FillEllipse(new SolidBrush(Color.Black),Pt1.X,Pt1.Y,5,5);               

     }

拖動一個方框

        PointF p1=new PointF();

        PointF p2=new PointF();

        System.Drawing.Pen myPen;

        System.Drawing.Pen myPen1;

        System.Drawing.Pen myPen2;

        System.Drawing.Graphics g1;

        int dl;

 

        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            p1.X=e.X;

            p1.Y=e.Y;

            dl=1;

        }

 

        private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            p2.X=e.X;

            p2.Y=e.Y;

            g1.DrawRectangle(myPen,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

            dl=0;

        }

 

        private void Form1_Load(object sender, System.EventArgs e)

        {

            myPen = new System.Drawing.Pen(System.Drawing.Color.Red,2);

            myPen1 = new System.Drawing.Pen(System.Drawing.Color.Yellow,1);

            myPen2 = new System.Drawing.Pen(this.BackColor,1);

            g1 = this.CreateGraphics();

            dl=0;

        }

 

        private void Form1_Closed(object sender, System.EventArgs e)

        {

            myPen.Dispose();

            myPen1.Dispose();

            myPen2.Dispose();

            g1.Dispose();

        }

 

        private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            if (dl==1)

            {

                g1.DrawRectangle(myPen2,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

                p2.X=e.X;

                p2.Y=e.Y;

                g1.DrawRectangle(myPen1,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

            }

      }

動態畫方框

        PointF p1=new PointF();

        PointF p2=new PointF();

        System.Drawing.Pen myPen;

        System.Drawing.Pen myPen1;

        System.Drawing.Pen myPen2;

        System.Drawing.Graphics g1;      

        int dl;

 

        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            p1.X=e.X;

            p1.Y=e.Y;

            dl=1;

        }

 

        private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            p2.X=e.X;

            p2.Y=e.Y;

            g1.DrawRectangle(myPen,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

            dl=0;

        }

 

        private void Form1_Load(object sender, System.EventArgs e)

        {

            myPen = new System.Drawing.Pen(System.Drawing.Color.Red,2);

            myPen1 = new System.Drawing.Pen(System.Drawing.Color.Yellow,1);

            myPen2 = new System.Drawing.Pen(this.BackColor,1);

            g1 = this.CreateGraphics();

            dl=0;

        }

 

        private void Form1_Closed(object sender, System.EventArgs e)

        {

            myPen.Dispose();

            myPen1.Dispose();

            myPen2.Dispose();

            g1.Dispose();

        }

 

        private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)

        {

            if (dl==1)

            {

                g1.DrawRectangle(myPen2,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

                p2.X=e.X;

                p2.Y=e.Y;

                g1.DrawRectangle(myPen1,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

            }

     }

 

讀取等值線文件畫圖

在Form1上放置控件Button1,picBox1(PictureBox),Form1.cs程序如下:

static void Main()

         {

              Application.Run(new Form1());

         }

        

         public string ss1;

 

         //找到第一個字符串,直到空格或者行尾

          string Qu1()

         {

              int i=0;

              bool cbl=true;

              int ls=ss1.Length;

              while((i<ls)&(cbl))

              {

                   char c1=ss1[i];

                   string s1=Convert.ToString(c1);

                   if (s1.Equals(" "))

                       cbl=false;

                   i++;

              }

              string s2=ss1.Remove(i,ls-i);

              ss1=ss1.Remove(0,i-1);

//            MessageBox.Show("ss1="+ss1);

              return s2;

         }

 

         private void button1_Click(object sender, System.EventArgs e)

         {

              string sfile = @"D:\chen\f8.txt";

              String s0,s1;

              int i,j,k;

              float x1,y1;

              bool Bl=true;

              PointF [,] pta = new PointF[200,2000];

 

              if (!File.Exists(sfile))

              {

                   MessageBox.Show("File does not exist.");

                   return;

              }

 

              //畫線設置

              System.Drawing.Pen myPen;

              float k1=0.08F;

              float k2=0.08F;

              float x0=0;

              float y0=0;

              myPen = new System.Drawing.Pen(System.Drawing.Color.Red);

              myPen.Width =1;

              System.Drawing.Graphics formGraphics = picBox1.CreateGraphics();

 

              StreamReader sr = File.OpenText(sfile);

              s0=sr.ReadLine();

              s0=sr.ReadLine();

              s0=sr.ReadLine();

 

              //讀取數值文件

              k=0;

              s0=sr.ReadLine();

              ss1=s0.Trim();

              while (s0!=null)

              {

                   i=0;

                   while (Bl)

                   {                     

                       s1=Qu1();

                       x1=Convert.ToSingle(s1);

                       ss1=ss1.Trim();

                       s1=Qu1();

                       y1=Convert.ToSingle(s1);

                       pta[k,i] = new PointF( x0+x1*k1, y0+y1*k2);

                       i++;

                       s0=sr.ReadLine();

                       ss1=s0.Trim();

                       if (ss1.Equals("-1"))

                            Bl=false;

                   }

                   Bl=true;

                   PointF[] cPoints=new PointF[i+1];

                   for (j=0;j<i;j++)

                   {

                       cPoints[j]=pta[k,j];

                   }

                   cPoints[i]=pta[k,0];  

                   k++;

                   //畫線

                   formGraphics.DrawLines(myPen, cPoints);

                   s0=sr.ReadLine();

                   if(s0!=null)

                       ss1=s0.Trim();

              }

              myPen.Dispose();

              formGraphics.Dispose();

              sr.Close();

     }

f8.txt格式:

0.00    0.00   8895.00   8895.00

25 28 29 29.5 30.5 31 32 35

5644.20 4625.40   32.00

  5633.50 4641.57   32.00

  5628.85 4655.05   32.00

  5633.50 4681.35   32.00

  5634.67 4684.70   32.00

  5663.15 4703.27   32.00

  5692.80 4700.70   32.00

  5714.98 4684.70   32.00

  5722.45 4668.68   32.00

  5726.26 4655.05   32.00

  5722.45 4640.66   32.00

  5714.23 4625.40   32.00

  5692.80 4612.07   32.00

  5663.15 4613.03   32.00

  5644.20 4625.40   32.00

  5644.20 4625.40   32.00

-1

2463.28 8895.00   25.00

  2487.03 8865.35   25.00

  2490.60 8860.86   25.00

……

 

 

十、其它常用方法

時間處理

間隔計算

DateTime oldDate = new DateTime(2002,7,15);

DateTime newDate = DateTime.Now;

 

// Difference in days, hours, and minutes.

TimeSpan ts = newDate - oldDate;

// Difference in days.

int differenceInDays = ts.Days;

Console.WriteLine("Difference in days: {0} ", differenceInDays);

注意,TimeSpan是系統基礎類。

利用時間判斷

        public  static bool JM(DateTime T0,int ii)

        {

            bool Bl=false;

            DateTime T1 = DateTime.Now;           

            TimeSpan ts = T1-T0;

            if (ts.Days>ii)

                Bl=true;

            return Bl;

     }

 

         DateTime oldDate = new DateTime(2007,1,29); //起始時間

         if(Common1.JM(oldDate,100)) //有效期100天

         {

              MessageBox.Show("試用版到期,請和北京派得偉業公司聯系,電話010-51503625");

              Application.Exit();

     }

Timer類

以下程序在每隔2秒顯示一個MessageBox提示。其中TimerEventProcessor方法在timer開始后就自動運行。

        static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

        static int alarmCounter = 1;

        static bool exitFlag = false;

 

        private static void TimerEventProcessor(Object myObject,EventArgs myEventArgs)

        {

            myTimer.Stop();

            if(MessageBox.Show("繼續?","計數:"+alarmCounter,MessageBoxButtons.YesNo)==DialogResult.Yes)

            {

                alarmCounter +=1;

                myTimer.Enabled = true;

            }

            else

                exitFlag = true;

        }

      

        private void button1_Click(object sender, System.EventArgs e)

        {

            myTimer.Tick += new EventHandler(TimerEventProcessor);

            myTimer.Interval = 2000;

            myTimer.Start();

            while(exitFlag == false)

            {

                // Processes all the events in the queue.

                Application.DoEvents();

            }

        }

延時程序

以下為延時程序,單位為毫秒。由於ts.Milliseconds數值在大於1000時出錯,所以要轉換成ts.Seconds。

        public void TimeDelay(int it)

        {

            bool Bl=true;

            DateTime T1,T0;

            TimeSpan ts;

            int it0;

 

            T0 = DateTime.Now;         

            while(Bl)

            {

                T1 = DateTime.Now;  

                ts=T1-T0;

                if (it>1000)

                {

                    it0=Convert.ToInt32(it/1000);

                    if (ts.Seconds>it0)

                        Bl=false;

                }

                else

                    if (ts.Milliseconds>it)

                        Bl=false;

                Application.DoEvents();

            }  

        }

      

        private void button1_Click(object sender, System.EventArgs e)

        {

            MessageBox.Show("開始");

            TimeDelay(2900);

            MessageBox.Show("時間到。");

        }

注意:在延時程序沒有完成前,不能退出。

dll文件調用

基本概念

動態鏈接庫 (DLL) 在運行時鏈接到程序。本程序通過兩個cs文件生成一個MyLibrary.DLL的庫文件。

Add.cs:為源文件,其中包含 Add(long i, long j) 方法。該方法返回參數之和。包含 Add 方法的 AddClass 類是命名空間 MyMethods 的成員。

Mult.cs:為源文件,其中包含 Multiply(long x, long y) 方法。該方法返回參數之積。包含 Multiply 方法的 MultiplyClass 類也是命名空間 MyMethods 的成員。

MyClient.cs:包含 Main 方法的文件。它使用 DLL 文件中的方法來計算運行時參數的和與積。

源程序

文件:Add.cs

// Add two numbers

using System;

namespace MyMethods

{

 public class AddClass

 {

  public static long Add(long i, long j)

  {

   return(i+j);

  }

 }

}

文件:Mult.cs

// Multiply two numbers

using System;

namespace MyMethods

{

 public class MultiplyClass

 {

  public static long Multiply(long x, long y)

  {

   return (x*y);

  }

 }

}

文件:MyClient.cs

// Calling methods from a DLL file

using System;

using MyMethods;

class MyClient

{

 public static void Main(string[] args)

 {

  Console.WriteLine("Calling methods from MyLibrary.DLL:");

  if (args.Length != 2)

  {

   Console.WriteLine("Usage: MyClient <num1> <num2>");

   return;

  }

  long num1 = long.Parse(args[0]);

  long num2 = long.Parse(args[1]);

  long sum = AddClass.Add(num1, num2);

  long product = MultiplyClass.Multiply(num1, num2);

  Console.WriteLine("The sum of {0} and {1} is {2}",

       num1, num2, sum);

  Console.WriteLine("The product of {0} and {1} is {2}",

      num1, num2, product);

 }

}

此文件包含使用 DLL 方法 Add 和 Multiply 的算法。它首先分析從命令行輸入的參數 num1 和 num2。然后使用 AddClass 類中的 Add 方法計算和,使用 MultiplyClass 類中的 Multiply 方法計算積。

請注意,文件開頭的 using 指令使您得以在編譯時使用未限定的類名來引用 DLL 方法,例如:

MultiplyClass.Multiply(num1, num2);

否則,必須使用完全限定名,例如:

MyMethods.MultiplyClass.Multiply(num1, num2);

編譯

若要生成文件 MyLibrary.DLL,使用以下命令行編譯文件 Add.cs 和文件 Mult.cs:

csc /target:library /out:MyLibrary.DLL Add.cs Mult.cs

如果對於一個文件以及缺省dll文件名,可以用:

csc /target:library Mult.cs

這樣生成一個Mult.dll的文件。

若要生成可執行文件 MyClient.exe,請使用以下命令行:

csc /out:MyClient.exe /reference:MyLibrary.DLL MyClient.cs

使用命令行編譯文件,在【開始】/【程序】/【Microsoft Visual Studio .NET 2003】/【Visual Studio .NET工具】/【Visual Studio .NET命令提示】。

默認目錄為當前用戶目錄。如果你使用Administrator,則目錄為C:\Documents and Settings\Administrator。你可以把幾個cs文件拷貝到這個目錄中。

執行

若要運行程序,請輸入 EXE 文件的名稱,文件名的后面跟兩個數字,例如:

MyClient 1234 5678

運行結果為:

Calling methods from MyLibrary.DLL:

The sum of 1234 and 5678 is 6912

The product of 1234 and 5678 is 7006652

自動編譯dll

建立一個bat文件如下:

c:\windows\microsoft.net\framework\v1.1.4322\csc.exe /target:library contour01.cs

就可以自動把contour01.cs編譯成contour01.dll了。

 

在IDE中調用dll

把以上的文件編譯成MyLibrary.DLL后,在一個控制台應用程序中使用MyClient.cs。先引用MyLibrary.DLL,然后修改程序為:

using System;

using MyMethods;

class MyClient

{

     public static void Main(string[] args)

     {

         Console.WriteLine("Calling methods from MyLibrary.DLL:");

         long num1 = 100;

         long num2 = 550;

         long sum = AddClass.Add(num1, num2);

         long product = MultiplyClass.Multiply(num1, num2);

         Console.WriteLine("The sum of {0} and {1} is {2}",

              num1, num2, sum);

         Console.WriteLine("The product of {0} and {1} is {2}",

              num1, num2, product);

     }

}

運行結果和以前一樣。

在C#中調用dll

1.編譯dll文件。

2.把dll文件拷貝到工作文件夾下面。

3.在右邊文件夾的【引用】上右擊,選擇【添加引用】,在【com】中瀏覽選擇,即可添加。也可以在菜單【項目】/【添加引用】上添加。

4.如果需要修改,需要把管理員目錄下的dll文件刪除,再次生成。

 

創建自定義控件

定義控件類

定義從 System.Windows.Forms.Control 派生的類。

public class FirstControl:Control{...}

定義屬性

以下代碼片段定義名為 TextAlignment 的屬性,FirstControl 使用該屬性來定義從 Control 繼承的 Text 屬性的顯示格式。

// ContentAlignment is an enumeration defined in the System.Drawing

// namespace that specifies the alignment of content on a drawing

// surface.

private ContentAlignment alignment = ContentAlignment.MiddleLeft;

 

public ContentAlignment TextAlignment {

   get {

      return alignment;

   }

   set {

      alignment = value;

      // The Invalidate method invokes the OnPaint method described

      // in step 3.

      Invalidate();

   }

}

在設置更改控件外觀顯示的屬性時,必須調用 Invalidate 方法來重新繪制該控件。Invalidate 是在基類 Control 中定義的。

重寫OnPaint 方法

重寫從 Control 繼承的受保護的 OnPaint 方法,以便為控件提供呈現邏輯。如果不改寫 OnPaint,您的控件將無法自行繪制。在下列代碼片段中,OnPaint 方法顯示了從 Control 繼承的具有默認對齊方式的 Text 屬性。

public class FirstControl : Control{

   public FirstControl() {...}

   protected override void OnPaint(PaintEventArgs e) {

      base.OnPaint(e);

      e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, style);

   }

}

提供控件屬性

屬性可使可視化設計器在設計時適當地顯示控件及其屬性和事件。以下代碼片段將屬性應用於 TextAlignment 屬性。在 Microsoft Visual Studio .NET 這樣的設計器中,Category 屬性(如代碼片段所示)使該屬性顯示在邏輯類別中。在選擇 TextAlignment 屬性時,Description 屬性使說明字符串顯示在“屬性”窗口的底部。

 [

Category("Alignment"),

Description("Specifies the alignment of text.")

]

public ContentAlignment TextAlignment {...}

提供控件資源

通過使用編輯器選項(C# 中為 /res),可以為控件提供諸如位圖之類的資源來打包控件的資源。在運行時,使用 System.Resources.ResourceManager 類的方法可檢索該資源。有關創建和使用資源的更多信息,請參見 .NET 示例 – 如何獲取:資源快速入門。

編譯和部署控件

要編譯和部署 FirstControl,請執行以下步驟:

將下列示例中的代碼保存到源文件(如 FirstControl.cs)。

將源代碼編譯成程序集,並將其保存到應用程序的目錄中。為了實現這一目的,需在包含源文件的目錄中執行以下命令。

csc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.cs

/t:library 編譯器選項告訴編譯器正在創建的程序集是一個庫(而不是一個可執行程序)。/out 選項用來指定程序集的路徑和名稱。/r 選項提供代碼所參考的程序集的名稱。在本示例中,創建了一個僅供您自己的應用程序使用的專用程序集。因此,您必須將其保存到您的應用程序的目錄中。有關打包和部署控件進行分發的更多信息,請參見部署 .NET Framework 應用程序。

示例程序

以下示例顯示了 FirstControl 的代碼。該控件包含在命名空間 CustomWinControls 中。命名空間提供了相關類型的邏輯分組。可以在新命名空間或現有的命名空間中創建控件。在 C# 中,using 聲明(在 Visual Basic 中,Imports)允許從命名空間訪問類型,而無須使用完全限定的類型名稱。在以下示例中,using 聲明允許代碼從 System.Windows.Forms 作為簡單控件存取 Control 類,而無須使用完全限定的名稱 System.Windows.Forms.Control。

namespace CustomWinControls {

   using System;

   using System.ComponentModel;

   using System.Windows.Forms;

   using System.Drawing;

   public class FirstControl : Control {

      private ContentAlignment alignment = ContentAlignment.MiddleLeft;

     

      [

       Category("Alignment"),

       Description("Specifies the alignment of text.")

      ]

      public ContentAlignment TextAlignment {

         get {

            return alignment;

         }

         set {

            alignment = value;

            // The Invalidate method invokes the OnPaint method.

            Invalidate();

         }

      }

 

      // OnPaint aligns text, as specified by the

      // TextAlignment property, by passing a parameter

      // to the DrawString method of the System.Drawing.Graphics object.

      protected override void OnPaint(PaintEventArgs e) {

         base.OnPaint(e);

         StringFormat style = new StringFormat();

         style.Alignment = StringAlignment.Near;

         switch (alignment) {

            case ContentAlignment.MiddleLeft:

               style.Alignment = StringAlignment.Near;

               break;

            case ContentAlignment.MiddleRight:

               style.Alignment = StringAlignment.Far;

               break;

            case ContentAlignment.MiddleCenter:

               style.Alignment = StringAlignment.Center;

               break;

         }

         // Call the DrawString method of the System.Drawing class to write  

         // text. Text and ClientRectangle are properties inherited from

         // Control.

         e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, style);

      }

   }

}

在窗體上使用自定義控件

以下示例說明了一個使用 FirstControl 的簡單窗體。它創建了三個 FirstControl 實例,每個實例都有不同的 TextAlignment 屬性值。

將下列示例中的代碼保存到源文件(SimpleForm.cs)。

通過從包含該源文件的目錄中執行以下命令,將源代碼編譯成可執行的程序集。

csc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.cs

CustomWinControls.dll 是包含類 FirstControl 的程序集。該程序集必須與存取它的窗體源文件位於同一目錄中(SimpleForm.cs 或 SimpleForms.vb)。

使用下列命令執行 SimpleForm.exe。

SimpleForm

using System;

using System.Windows.Forms;

using System.Drawing;

using CustomWinControls;

 

class SimpleForm : Form {

   private FirstControl left;

   private FirstControl center;

   private FirstControl right;

  

   protected override void Dispose(bool disposing) {

      base.Dispose(disposing);

   }

 

   public SimpleForm() : base() {

      left = new FirstControl();

      left.Text = "Left";

      left.Location = new Point(50, 50);

      left.Size = new Size(50, 50);

      Controls.Add(left);

     

      center = new FirstControl();

      center.TextAlignment = ContentAlignment.MiddleCenter;

      center.Text = "Center";

      center.Location = new Point(125, 50);

      center.Size = new Size(50, 50);

      Controls.Add(center);

     

      right = new FirstControl();

      right.TextAlignment = ContentAlignment.MiddleRight;

      right.Text = "Right";

      right.Location = new Point(200, 50);

      right.Size = new Size(50, 50);

      Controls.Add(right);

   }

  

   [STAThread]

   public static void Main(string[] args) {

      Form form = new SimpleForm();

      form.Text = "Uses FirstControl";

      form.Size = new Size(400, 150);

      Application.Run(form);

   }

}

用戶控件

用途

用戶控件相當於帶界面的類模塊,並可以編譯成dll。具有以下優點:

1.可以把程序分離成內核部分和引用部分,便於開發和維護;

2.可以多進程調用;

3.安全性好。

自己創建的例子

自己創建一個簡單用戶控件的步驟為:

1.新建一個“Windows控件庫”的項目;

2.編寫控件程序,如需要傳遞參數,定義如下:

public PointF p1,p2;

3.在【生成】中生成dll;

4.用【文件】/【添加項目】/【新建項目】,新建一個使用控件項目,為“Windows應用程序”;

5.用【項目】/【添加引用】/【項目】,引用控件項目;

6.在【工具箱】/【我的用戶控件】中選擇生成的控件;

7.把使用項目設置為啟動;

8.編寫程序。如果傳遞參數,用:

        private void Form1_Load(object sender, System.EventArgs e)

        {

            userControl11.p1=new PointF(20,20);

            userControl11.p2=new PointF(100,200);

        }

然后可以在這個解決方案中隨意修改控件設計,只要運行調用程序,就可以自動編譯和加載控件了。如果修改了控件的界面,還需要重新生成和加載。

如果在單獨的使用程序中調用這個dll控件,則先需要添加引用,然后需要在“工具箱”上點擊右鍵,選擇【添加/移除項】,把這個控件添加到工具箱上,才可以添加到form上。

在使用程序中可以隨意調用控件中的方法。如果要在控件中調用使用程序中的方法,則可以使用一個傳遞參數,如 int bi,每次點擊事件時bi值改變。然后在使用程序中用一個timer控件,用事件timer1_Tick來監控bi的變化,來觸發一個方法。

inputBox方法

類定義

         public class InputBox : System.Windows.Forms.Form

         {

              private System.Windows.Forms.TextBox txtData;

              private System.Windows.Forms.Label lblInfo;

              private System.ComponentModel.Container components = null; 

 

              private InputBox()

              {

                   InitializeComponent();

              } 

 

              protected override void Dispose( bool disposing )

              {

                   if( disposing )

                   {

                       if(components != null)

                       {

                            components.Dispose();

                       }

                   }

                   base.Dispose( disposing );

              } 

 

              private void InitializeComponent()

              {

                   this.txtData = new System.Windows.Forms.TextBox();

                   this.lblInfo = new System.Windows.Forms.Label();

                   this.SuspendLayout();

                  

                   // txtData            

                   this.txtData.Font = new System.Drawing.Font("宋體", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));

                   this.txtData.Location = new System.Drawing.Point(19, 8);

                   this.txtData.Name = "txtData";

                   this.txtData.Size = new System.Drawing.Size(317, 23);

                   this.txtData.TabIndex = 0;

                   this.txtData.Text = "";

                   this.txtData.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtData_KeyDown);

                  

                   // lblInfo

                   this.lblInfo.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));

                   this.lblInfo.Location = new System.Drawing.Point(19, 32);

                   this.lblInfo.Name = "lblInfo";

                   this.lblInfo.Size = new System.Drawing.Size(317, 16);

                   this.lblInfo.TabIndex = 1;

                   this.lblInfo.Text = "按[Enter]鍵確認,按[Esc]鍵取消";

 

                   // InputBox

                   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                   this.ClientSize = new System.Drawing.Size(350, 48);

                   this.ControlBox = false;

                   this.Controls.Add(this.lblInfo);

                   this.Controls.Add(this.txtData);

                   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;

                   this.Name = "InputBox";

                   this.Text = "InputBox";

                   this.ResumeLayout(false);

              }

 

              //對鍵盤進行響應

              private void txtData_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)

              {

                   if(e.KeyCode == Keys.Enter)

                   {

                       this.Close();

                   }

                   else if (e.KeyCode == Keys.Escape )

                   {

                       txtData.Text = string.Empty ;

                       this.Close();

                   }

              }

 

              //顯示InputBox

              public static string ShowInputBox(string Title,string keyInfo)

              {

                   InputBox inputbox = new InputBox();

                   inputbox.Text =Title;

                   if (keyInfo.Trim() != string.Empty )

                       inputbox.lblInfo.Text =keyInfo;

                   inputbox.ShowDialog();

                   return inputbox.txtData.Text;

              }

         }       

普通調用

         private void button1_Click(object sender, System.EventArgs e)

         {

              string inMsg = InputBox.ShowInputBox("輸入信息",string.Empty );

              //對用戶的輸入信息進行檢查

              if (inMsg.Trim() != string.Empty )

              {

                   MessageBox.Show(inMsg);

              }

              else

              {

                   MessageBox.Show("輸入為空!");

              }

如果需要輸入一個int數值,則程序如下:

              string inMsg = InputBox.ShowInputBox("輸入信息",string.Empty );

              int a1;

              if (inMsg.Trim() != string.Empty )

              {

                   try

                   {

                       a1=Convert.ToInt32(inMsg.Trim());

                       MessageBox.Show(a1.ToString());

                   }

                   catch (Exception)

                   {

                       MessageBox.Show("輸入錯誤!繼續保持原有數據。");

                   }

              }

              else

              {

                   MessageBox.Show("輸入為空!");

          }

增加缺省值

在類中增加以下程序:

            public static string ShowInputBox(string Title,string keyInfo,string textInfo)

            {

                InputBox inputbox = new InputBox();

                inputbox.Text =Title;              

                inputbox.txtData.Text=textInfo;              

                if (keyInfo.Trim() != string.Empty )

                    inputbox.lblInfo.Text =keyInfo;

                inputbox.ShowDialog();

                return inputbox.txtData.Text;

            }

可以在調用時輸入textBox中的缺省值。

 

版本設置

在文件AssemblyInfo.cs中修改

[assembly: AssemblyVersion("2.1.1.*")]

則在最后生成的EXE文件中顯示版本號2.2.1.10803,最后一個號碼隨着每次編輯修改后遞增。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM