手机杀毒软件什么好-网页打不开是什么原因

writeline
2023年4月3日发(作者:笔记本内置无线网卡)

C#(WINFORM)学习

第1页

一、C#基础知识

类型和变量

类型

C#支持两种类型:“值类型”和“引用类型”。值类型包括简单类型(如

char、int和float等)、枚举类型和结构类型。引用类型包括类(Class)类

型、接口类型、委托类型和数组类型。

变量的类型声明

每个变量必须预先声明其类型。如

inta;

intb=100;

floatj=4.5;

strings1;

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

预定义类型

下表列出了预定义类型,并说明如何使用。

类型说明示例范围

object

所有其他类型的最终

基类型

objecto=null;

string

字符串类型;字符串是

Unicode字符序列

strings="hello";

sbyte8位有符号整型sbyteval=12;

-128到127

short16位有符号整型shortval=12;

-32,768到32,767

int32位有符号整型intval=12;

-2,147,483,648到

2,147,483,647

long64位有符号整型

longval1=12;

longval2=34L;

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

9,223,372,036,854,775,807

C#(WINFORM)学习

第2页

byte8位无符号整型byteval1=12;

0到255

ushort16位无符号整型ushortval1=12;

0到65,535

uint32位无符号整型

uintval1=12;

uintval2=34U;

0到4,294,967,295

ulong64位无符号整型

ulongval1=12;

ulongval2=34U;

ulongval3=56L;

ulongval4=78UL;

0到

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

float单精度浮点型

floatval=1.23F;7

±1.5×10−45到

±3.4×1038

double双精度浮点型

doubleval1=1.23;

doubleval2=

4.56D;15-16

±5.0×10−324到

±1.7×10308

bool

布尔型;bool值或为

真或为假

boolval1=true;

boolval2=false;

char

字符类型;char值是

一个Unicode字符

charval='h';

decimal

精确的小数类型,具有

28个有效数字

decimalval=

1.23M;28-29

±1.0×10−28到

±7.9×1028

DateTime

变量转换

简单转换:

floatf=100.1234f;

可以用括号转换:

shorts=(short)f

也可以利用Convert方法来转换:

strings1;

s1=ng(a);

(s1);

常用Convert方法有:

C#备注

ean

C#(WINFORM)学习

第3页

Time

mal

le

16

32

64

e

le

ng

16

32

64

Math类

常用科学计算方法:

C#备注

绝对值

开方

取整,四舍五入

取整,放弃小数

余弦

正弦

正切

返回e的指定次幂

对数

(x,y)

数字x的y次幂

(x,y)返回较大者

(x,y)

返回较小者

C#(WINFORM)学习

第4页

枚举型

一般为字符串,可以定义带数字的枚举型,示例为:

enumColor

{

Red=1,

Blue=2,

Green=3

}

classShape

{

publicintFill(Colorcolor)

{

intii;

switch(color)

{

:

ii=10;

break;

:

ii=11;

break;

:

ii=12;

break;

default:

ii=-1;

break;

}

returnii;

}

}

privatevoidbutton1_Click(objectsender,rgse)

{

inti;

Shapes1=newShape();

i=((Color)2);

//i=();

(ng());

}

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

C#(WINFORM)学习

第5页

C#关键字

abstracteventnewstruct

asexplicitnullswitch

baseexternobjectthis

boolfalseoperatorthrow

breakfinallyouttrue

bytefixedoverridetry

casefloatparamstypeof

catchforprivateuint

charforeachprotectedulong

checkedgotopublicunchecked

classifreadonlyunsafe

constimplicitrefushort

continueinreturnusing

decimalintsbytevirtual

defaultinterfacesealedvolatile

delegateinternalshortvoid

doissizeofwhile

doublelockstackalloc

elselongstatic

enumnamespacestring

数组

定义

数组是一种排列有序的数据结构,包含于数组中的变量被称为数组的元素,

它们都有相同的类型。

数组声明

int[]array1=newint[5];

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

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

数组引用

array1[0]="a1";

C#(WINFORM)学习

第6页

注意,如果定义数组为int[5],则从0~4。

数组长度

gth(1)

数组赋值

可以从一个已经赋值的数组array2向未赋值的同等数组array1赋值,用

array1=array2;

这时,array1就变成和array2一样的数组了。

集合

集合的使用

集合可以看成是可以随意添加的数组,因此凡是在使用数组的场合,都可以

使用集合。而且集合的元素可以是任意对象,操作也比数组灵活的多。

使用集合时,必须注意集合的生命期问题。如果有两个集合L1和L2,使用

L1=L2;

后,只要L2生命期没有终结,它的以后的变化就可能会影响到L1的数值。因

此在赋值后应该及时销毁或者初始化L2,以免发生不可预见的错误。

比较

使用Contains方法。

ArrayListArray1=newArrayList();

("as");

boolb1=ns("as");

(ng());

找到集合中数量最多的一个元素

利用方法来查找,可以返回两个变量。

C#(WINFORM)学习

第7页

objectJmax0(ArrayListv11,refintjj)

{

inti;

objectj0=0;

ArrayListy11=newArrayList();//各个不同的元素的集合

int[]y12=newint[];//记录各个元素数量的数组

intxmax=0;//最大的一个元素的数量

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

{

j0=(object)v11[i];

if(ns(j0))

{

y12[f(j0)]++;

}

else

{

(j0);

y12[-1]=1;

}

}

xmax=y12[0];

j0=(object)y11[0];

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

{

if(y12[i]>xmax)

{

xmax=y12[i];

j0=(object)y11[i];

}

}

jj=xmax;

returnj0;

}

privatevoidbutton1_Click(objectsender,rgse)

{

ArrayListArray1=newArrayList();

intjj=0;

doublej0=0;

objectj1=0;

j0=2.3;

C#(WINFORM)学习

第8页

(j0);

j0=2.3;

(j0);

j0=1.000f;

(j0);

j0=2.3;

(j0);

j0=1;

(j0);

j1=Jmax0(Array1,refjj);

(ng()+""+ng());

}

运算符和判断

判断

if(x>10)

if(y>20)

("Statement_1");

else

("Statement_2");

关系运算符

<,<=,>,>=

等于:==

不等于:!=

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

逻辑运算符

与:a&b

或:a|b

非:!A

C#(WINFORM)学习

第9页

模数运算符

模数运算符(%)计算第二个操作数除第一个操作数后的余数。所有数值类

型都具有预定义的模数运算符。如

ine(5%2);//=1

ine(-5%2);//=-1

ine(5.0%2.2);//=0.6

ine(-5.2%2.0);//=-1.2

经常用模数运算符来判断整数为奇数(=1)或偶数(=0)。

循环

无条件循环

intsum,x;

sum=0;

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

{

sum+=x;

}

有条件循环

privatevoidbutton1_Click(objectsender,rgse)

{

intsum=0;

intx=0;

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

{

x++;

sum+=x;

}

strings2=ng(x);

(s2);

}

运行显示14。

如果改为

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

C#(WINFORM)学习

第10页

运行显示20。

多重选择

switch(i)

{

case0:

CaseZero();

break;

case1:

CaseOne();

break;

default:

CaseOthers();

break;

}

每个case后面,必须有break或者goto,不允许贯穿。

Goto

goto语句将程序控制直接传递给标记语句。

for(inti=0;i

for(intj=0;j

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

gotoFound;

ine("Thenumber{0}wasnotfound.",myNumber);

gotoFinish;

Found:

ine("Thenumber{0}isfound.",myNumber);

C#(WINFORM)学习

第11页

Finish:

ine("Endofsearch.");

foreach

foreach语句为对数组或者集合中的每个元素重复执行嵌入语句。对于数组

示例为:

usingSystem;

classMainClass

{

publicstaticvoidMain()

{

intodd=0,even=0;

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

foreach(intiinarr)

{

if(i%2==0)

even++;

else

odd++;

}

ine("Found{0}OddNumbers,and{1}EvenNumbers.",

odd,even);

}

}

break

退出当前的循环。

也可以退出当前模块,使用一个空while循环,示例如下:

C#(WINFORM)学习

第12页

voidCH(doubleX1)

{

boolbl=true;

while(bl)

{

if(X1==1.0)

{

("YES");

break;

}

("no");

bl=false;

}

}

输出格式

简单格式

对于控制台程序:

ine("Found{0}OddNumbers,and{1}EvenNumbers.",odd,

even);

对于普通系统:

intx=1,y=2;

strings0;

s0=("Found{0}OddNumbers,and{1}EvenNumbers.",x,y);

(s0);

format

用指定字符和数字说明格式。C(货币格式,用NumberFormatInfo指定种类)

D(十进制整数)E(科学计数法)F(固定点)G(常规)N(数字)P(百分比)

等。

tCulture=newCultureInfo("en-us");

doubleMyDouble=123456789;

C#(WINFORM)学习

第13页

ine(ng("C1"));

ine(ng("E"));

ine(ng("P"));

ine(ng("N3"));

ine(ng("F"));

运行显示:

$123,456,789.0

1.234568E+008

12,345,678,900.00%

123,456,789.000

123456789.00

还可以这样使用:

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

控制台程序

打开VisualC#.NET2003,选择【新建】/【项目】,或者选择【新建项目】

在VisualC#项目中选择【控制台应用程序】,选择程序名称和位置后,进入程

序界面(IDE)。

C#(WINFORM)学习

第14页

这时系统生成一个的程序文件。修改成以下:

usingSystem;

namespaceConsole2

{

//A"HelloWorld!"programinC

#classHello

{

staticvoidMain()

{

ine("HelloWorld!");

}

}

}

点击【调试】/【开始执行(不调试)】,就可以在DOS界面下看见结果。

C#(WINFORM)学习

第15页

二、使用控件

基本操作

添加控件

选择程序名称和位置后,进入程序的一个Form1界面。

从左边的【工具箱】/【Windows窗体】中,添加一个Label控件和一个Button

控件,双击Button1,添加程序如下:

privatevoidbutton1_Click(objectsender,rgse)

{

="iiii";

}

就可以查看运行效果了。

如果修改成

=+10;

就可以看见点击Button后,标签右移的效果。

控件的基本特性

工具箱的控件主要有Button(按钮)、Label(标签)、TextBox(文本框)、

RadioButton(单选按钮)、CheckBox(复选框)、ListBox(下拉框)等。

可以双击在Form上产生控件,也可以先点击,然后在Form上画矩形,决

定控件的大小。

控件的基本特性有事件、方法和属性,详见2.2。

控件的事件主要有Click(单击)、DoubleClick(双击)、MouseOver(鼠标

移过)等。

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

控件的主要属性有:

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

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

C#(WINFORM)学习

第16页

3.颜色和字体控制,主要有BackColor(背景颜色)、ForeColor(前景颜色)、

Font(字体)等;

4.名称控制,主要有Name(控件名字)、Caption(控件标题)等;

5.控件序号,主要有TabIndex(焦点的TAB顺序控制)、Index(控件数组

序号);

6.其它,主要有Enabled(决定控件是否激活,True或False)、ToolTipText

(鼠标移过时显示的文字)等。

消息框MessageBox

简单使用方法

使用消息框,可以在程序运行到这里时弹出一个对话框,显示指定的文字。

是向外输出信息的重要方式。

("def");

通用方法

消息框输出必须为string类型,如果不是,则需要转换:

strings1;

s1=ng(a);

(s1);

C#(WINFORM)学习

第17页

可以用以下函数简化使用方法:

privatevoidmsgbox(objecta)//用消息框显示任意一个数

{

strings1;

s1=ng(a);

(s1);

}

较多使用方法

("name","NameEntry",,

ation);

其中第二项开始依次为消息框的标题、按钮样式、图标样式。

MessageBoxButtons的数值为枚举型,为OK(缺省)、AbortRetryIgnore、

OKCancel、RetryCancel、YesNo、YesNoCancel。

获取返回信息

privatevoidbutton2_Click(objectsender,rgse)

{

DialogResultresult;

result=("name","NameEntry",,

on);

(ng());

}

如果要参与判断,则用

stringls=ng();

完全使用方法

本例检查textBox1中输入文本没有,如果没有就提示,并可以获取返回信

息。

privatevoidbutton1_Click(objectsender,rgse)

{

if(==0)

{

stringmessage="thisoperation?";

stringcaption="NoServerNameSpecified";

MessageBoxButtonsbuttons=;

C#(WINFORM)学习

第18页

DialogResultresult;

result=(this,message,caption,buttons,

on,1,

lign);

if(result==)

();

}

}

}

文本框

基本功能

文本框主要是用来输入和显示文字的。

添加一个TextBox,系统自己产生名字textBox1,程序如下:

privatevoidbutton1_Click(objectsender,rgse)

{

();

}

运行时,就可以在消息框中显示文本框输入的字符串。

TextBox一般显示单行,如果把属性Multiline改为Ture,还可以显示多行数

字。

输入数字

输入数字需要转换:

inta;

strings1;

a=16();

a=a+5;

s1=ng(a);

(s1);

C#(WINFORM)学习

第19页

初始化

文本框的初始化就是向文本框赋初始值。可以从事件过程里写入,也可以在

IDE的右边属性栏里输入,但是推荐采用在Form初始化时写入。

publicForm1()

{

InitializeComponent();

//TODO:在InitializeComponent调用后添加任何构造函数代码

="";

}

窗体调用

简单调用

上面的例子都是在一个窗体中,实际程序需要几十甚至上百个窗体。以下例

子创建两个窗体,然后实现相互调用。

在Form1中添加两个Button,一个标题为调用,一个标题为退出。

使用【项目】/【添加窗体】,添加一个窗体,缺省名称为Form2。添加一个

Button,标题为返回。

窗体1程序为:

privatevoidbutton1_Click(objectsender,rgse)

{

Form2Nform2=newForm2();

();

();

}

privatevoidbutton2_Click(objectsender,rgse)

{

();

}

窗体2程序为:

privatevoidbutton1_Click(objectsender,rgse)

{

Form1Nform1=newForm1();

();

C#(WINFORM)学习

第20页

();

}

运行程序,可以在两个窗体之间来回调用,按“退出”就可以退出程序。

程序运行时,如果发现窗体位置不固定,这时需要在窗体的StartPosition属

性上设置窗体固定位置,一般为屏幕中央。

注意,两个窗体要在一个命名空间,否则要引用。

传递参数调用

在Form1中添加一个Button1和一个textBox1,程序为:

privateForm2otherForm=newForm2();

privatevoidGetOtherFormTextBox()

{

=;

}

privatevoidbutton1_Click(objectsender,rgse)

{

GetOtherFormTextBox();

}

在Form2中添加一个textBox1,在

InitializeComponent();

后面添加一个赋值语句为:

="abd";

然后添加一个属性:

publicTextBoxTextBox1

{

get

{

returntextBox1;

}

}

运行时,点击Form1中的Button1,可以把Form2的TextBox的数值取到

Form1的TextBox中来。

C#(WINFORM)学习

第21页

复杂传递参数

本例是移动一个标签,在两个Form之间来回移动。

先设计Form1如下:

设计Form2,除了少了一个退出按钮外,其余相同。

在Form1的InitializeComponent()下面加上窗体定位语句:

PointtempPoint=newPoint(100,100);

pLocation=tempPoint;

然后把Form1的StartPosition属性改为Manual。其余程序为:

publicLabelL2

{

get

{

returnlabel1;

}

set

{

label1=value;

}

}

privatevoidbutton2_Click(objectsender,rgse)

{

C#(WINFORM)学习

第22页

Form2otherForm=newForm2();

=+10;

if(>=-10)

{

();

=;

();

}

}

privatevoidbutton1_Click(objectsender,rgse)

{

=-10;

}

privatevoidbutton3_Click(objectsender,rgse)

{

=-10;

}

privatevoidbutton4_Click(objectsender,rgse)

{

=+10;

}

privatevoidbutton5_Click(objectsender,rgse)

{

();

}

同样在Form2的InitializeComponent()下面加上窗体定位语句:

PointtempPoint=newPoint(300,100);

pLocation=tempPoint;

然后把Form2的StartPosition属性改为Manual。其余程序为:

publicLabelL1

{

get

{

returnlabel1;

}

set

{

label1=value;

C#(WINFORM)学习

第23页

}

}

privatevoidbutton2_Click(objectsender,rgse)

{

=+10;

}

privatevoidbutton1_Click(objectsender,rgse)

{

Form1otherForm1=newForm1();

=-10;

if(<=-10)

{

();

=;

=-20;

();

}

}

privatevoidbutton3_Click(objectsender,rgse)

{

=-10;

}

privatevoidbutton4_Click(objectsender,rgse)

{

=+10;

}

动态产生窗体

publicvoidCreateMyForm()

{

Formform1=newForm();

Labellabel1=newLabel();

Buttonbutton1=newButton();

TextBoxtext1=newTextBox();

="确定";

on=newPoint(110,220);

on=newPoint(50,100);

on=newPoint(150,100);

C#(WINFORM)学习

第24页

="请输入";

="数据";

rderStyle=ialog;

lBox=false;

Button=button1;

osition=Screen;

(button1);

(text1);

(label1);

alog();

ls=;

}

privatevoidbutton2_Click(objectsender,rgse)

{

CreateMyForm();

(ls);

}

ToolBar

普通使用

在窗体上加上ToolBar

界面修改后的问题

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

(toolBarButton1);

(toolBarButton2);

(toolBarButton3);

//Addtheevent-handlerdelegate.

Click+=newToolBarButtonClickEventHandler

(r1_ButtonClick);

或者把原有的程序

C#(WINFORM)学习

第25页

ge(rButton[]{

rButton1,rButton2,rButton3});

改变位置,到toolBar1设置的最下面。

全部设置程序为:

wnArrows=true;

on=(0,0);

="toolBar1";

olTips=true;

=(592,42);

ex=0;

Size=(60,50);

//

//toolBarButton1

//

="Open";

=Button;

//

//toolBarButton2

//

="Save";

=Button;

//

//toolBarButton3

//

="Print";

(toolBarButton1);

(toolBarButton2);

(toolBarButton3);

Click+=newToolBarButtonClickEventHandler

(r1_ButtonClick);

设置按钮大小

如下设置,可以正常居中显示9号字体。

Size=(60,50);

用程序实现

可以用程序实现按钮的增加,但是无法全部实现自动化。

C#(WINFORM)学习

第26页

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

上。

voidtoolBarSet()

{

//添加按钮

ToolBarButtontoolBarButton1=newToolBarButton();

ToolBarButtontoolBarButton2=newToolBarButton();

ge(new

rButton[]{toolBarButton1,toolBarButton2});

wnArrows=true;

ist=imageList1;

=(408,37);

ex=0;

Click+=new

rButtonClickEventHandler(toolBar1_ButtonClick);

//toolBarButton1

ndex=0;

pText="放大";

//toolBarButton2

ndex=1;

pText="缩小";

}

privatevoidForm1_Load(objectsender,rgse)

{

toolBarSet();

}

privatevoidtoolBar1_ButtonClick(objectsender,

rButtonClickEventArgse)

{

switch(f())

{

case0://放大

("放大");

break;

case1://缩小

("缩小");

break;

default:

("other");

break;

C#(WINFORM)学习

第27页

}

}

listBox

普通调用

在窗体上放置一个listBox1,一个button1和一个label1。以下程序实现添加

选项,双击选项就可以显示你的选择:

privatevoidbutton1_Click(objectsender,rgse)

{

();

("");

("选择1");

("选择2");

edIndex=0;

}

privatevoidlistBox1_DoubleClick(objectsender,rgse)

{

=ng();

}

第一项是一个缺省空项,允许用户不选取退出。

Items是一个集合,因此增减选项可以按照集合那样操作。

用数组添加选项

[]ItemObject=[10];

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

{

ItemObject[i]="Item"+i;

}

ge(ItemObject);

C#(WINFORM)学习

第28页

ScrollBar

基本定义

ScrollBar是滚动条控件,分成HScrollBar(水平)和VScrollBar(垂直)两

种。有些控件如ListBox,TextBox等可以自动添加滚动条,但是有些控件则需

要用程序添加。主要属性意义为:

Value:滚动条的数值,反映当前移动块的位置。初始值设定后,运行时停

留在这个位置。运行时拉动滚动条,由Scroll事件的ue参数传递过来。

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

Minimum:Value的最小值,即端点的数值。如果Maximum=100,Minimum=0,

LargeChange=10,则从第一个端点开始Value=0,到另一个端点的Value=91。

SmallChange:每次点击移动的数值,一般为1。

LargeChange:移动块的长度,一般为10。

和PicturBox控件一起使用

floatvi;//每个单位的移动距离

floatvk=0.8f;//PicturBox显示高度和实际高度的比例

intt0,ti;//PicturBox显示Top和Height。

privatevoidvScrollBar1_Scroll(object

sender,EventArgse)

{

=32(ue*vi);

=ti+32(ue*vi);

}

privatevoidbutton1_Click(objectsender,rgse)

{

ButtonoButton;

TextBoxoTextBox;

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

{

oButton=newButton();

="按钮"+ng();

on=(50,i*50);

+=andler(oButton_Click);

C#(WINFORM)学习

第29页

(oButton);

oTextBox=newTextBox();

=oTextBox;

="1000";

on=(150,i*50);

(oTextBox);

}

}

privatevoidoButton_Click(objectsender,rgse)

{

Buttonbtn=(Button)sender;

TextBoxtxt=(TextBox);

=ng(32()+1);

}

privatevoidForm1_Load(objectsender,rgse)

{

vi=vk*/m;

t0=;

ti=;

}

Panel

基本定义

Windows窗体Panel(面板)控件用于为其他控件提供可识别的分组。在设

计时所有控件均可轻松地移动,当移动Panel控件时,它包含的所有控件也将

移动。分组在一个面板中的控件可以通过面板的Controls属性进行访问。

Panel控件类似于GroupBox控件;但只有Panel控件可以有滚动条,而

且只有GroupBox控件显示标题。

将AutoScroll属性设置为true,可以自动显示滚动条。但是这时右边界和

下边界顶头,不是太好看。这时需要增加一个不可见的控件或者图像来调整。

下例在Panel上用程序添加几个控件,产生滚动效果:

privatevoidbutton1_Click(objectsender,rgse)

C#(WINFORM)学习

第30页

{

ButtonoButton;

TextBoxoTextBox;

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

{

oButton=newButton();

="按钮"+ng();

on=(50,i*50);

+=andler(oButton_Click);

(oButton);

oTextBox=newTextBox();

=oTextBox;

="1000";

on=(150,i*50);

(oTextBox);

}

//增加一个不可见按钮,调整右边界和下边界的位置

oButton=newButton();

on=(260,440);

=0;

=0;

(oButton);

}

privatevoidoButton_Click(objectsender,rgse)

{

Buttonbtn=(Button)sender;

TextBoxtxt=(TextBox);

=ng(32()+1);

}

在Panel控件上添加图像

在Panel控件上不能直接添加图像。需要在Panel控件上添加一个picturBox,

然后把其SizeMode设置为AutoSize(随着图像大小调整控件大小)就可以实现

图像的随意滚动察看。

在Panel控件上画图

Panel控件上也可以画图。但是滚动时遮盖的图像就消失了。这时候需要在

Panel控件上添加一个picturBox,然后在picturBox上画图,然后用一个

LocationChanged事件,每次滚动时重画一遍即可:

C#(WINFORM)学习

第31页

Penpen1=newPen(,2);

Graphicsg1;

voiddrawLine()

{

PointFp1=newPointF(0,0);

PointFp2=newPointF(100,100);

ne(pen1,p1,p2);

}

privatevoidbutton2_Click(objectsender,rgse)

{

g1=Graphics();

drawLine();

}

privatevoidpictureBox1_LocationChanged(objectsender,

rgse)

{

drawLine();

}

菜单

普通应用

手工添加即可。可以直接在其上写各个菜单项的名字,双击可以添加程序,

使用非常方便。

特殊功能

1.在设计时向菜单项添加选中标记

对于在“菜单设计器”内选定的菜单项(三级菜单以下),单击该菜单项左侧

的区域,选中标记√。或者在“属性”窗口中将Checked属性设置为True。

以编程方式向菜单项添加选中标记

d=true;

2.在设计时向菜单项添加快捷键

在“菜单设计器”内选择菜单项。在“属性”窗口中,将Shortcut属性设置为

C#(WINFORM)学习

第32页

下拉列表中提供的值之一。

以编程方式向菜单项添加快捷键

ut=ut.F6;

3.向菜单项添加访问键

如键入“文件(&F)”,显示“文件(F)”。

若要定位到此菜单项,请按ALT键,将焦点移动到菜单栏,然后按该菜单

名称的访问键。当菜单打开并显示带访问键的项时,只需按该访问键就可选定该

菜单项。或者直接按ALT+主菜单的访问键。

4.将分隔线作为菜单项添加

在菜单设计器中,右击需要有分隔线的位置,然后选择“插入分隔符”。或者

在设置菜单项的Text属性(在“属性”窗口中、菜单设计器中或代码中)时,输

入短划线(–)使该菜单项成为分隔线。

其它控件

单选按钮

单选按钮是布置一组按钮,只能选择一组控件。

本例放置3个单选按钮,Text属性分别写上“已婚”、“未婚”和“离异”,

然后添加一个Label控件和一个Button控件,程序如下:

publicForm1()

{

InitializeComponent();

="请选择";

……

privatevoidbutton1_Click(objectsender,rgse)

{

if(d==true)

=;

elseif(d==true)

=;

else

=;

}

C#(WINFORM)学习

第33页

}

复选框

可以选择多个的一组控件。

本例放置2个复选按钮,Text属性分别写上“加粗”和“斜体”,然后添加

一个Label控件和一个Button控件,程序如下:

privatevoidbutton1_Click(objectsender,rgse)

{

if(d==true)

{

if(d==true)

=+;

elseif(d==false)

=;

}

else

if(d==true)

=;

elseif(d==false)

="";

}

C#(WINFORM)学习

第34页

程序产生checkBox

CheckBoxcheckBox1=newCheckBox();

voidcheckSet()

{

(checkBox1);

on=(50,64);

="checkBox1";

ex=2;

="图层1";

dChanged+=andler(checkBox1_CheckedChanged);

}

privatevoidbutton1_Click(objectsender,rgse)

{

checkSet();

}

privatevoidcheckBox1_CheckedChanged(objectsender,rgse)

{

if(d)

("yes");

else

("no");

}

如果要实现标题在左边,用

=90;

lign=Right;

要在其它控件显示:

oFront();

动态产生控件

以下程序动态动态产生一组Button和TextBox控件,以及点击Button的事

件。

privatevoidbutton2_Click(objectsender,rgse)

{

ButtonoButton;

TextBoxoTextBox;

C#(WINFORM)学习

第35页

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

{

oButton=newButton();

="按钮"+ng();

on=(50,i*50);

+=andler(oButton_Click);

(oButton);

oTextBox=newTextBox();

=oTextBox;

="1000";

on=(150,i*50);

(oTextBox);

}

}

privatevoidoButton_Click(objectsender,rgse)

{

Buttonbtn=(Button)sender;

TextBoxtxt=(TextBox);

=ng(32()+1);

}

Splitter

Windows窗体splitter控件用于在运行时调整停靠控件的大小。Splitter控

件常用于一类窗体,这类窗体上的控件所显示的数据长度可变,如Windows资

源管理器,它的数据窗格所包含的信息在不同的时间有不同的宽度。

如果一个控件可由splitter控件调整其大小,则当用户将鼠标指针指向该控

件的未停靠的边缘时,鼠标指针将更改外观,指示该控件的大小是可以调整的。

拆分控件允许用户调整该控件紧前面的停靠控件的大小。因此,为使用户能够在

运行时调整停靠控件的大小,请将要调整大小的控件停靠在容器的一条边缘上,

然后将拆分控件停靠在该容器的同一侧。

以下例子自动产生几个控件,可以在运行中调整大小。

privatevoidCreateMySplitControls()

{

TreeViewtreeView1=newTreeView();

ListViewlistView1=newListView();

Splittersplitter1=newSplitter();

C#(WINFORM)学习

第36页

=;

=;

ra=100;

e=75;

=;

("TreeViewNode");

("ListViewItem");

ge(newControl[]{listView1,splitter1,treeView1});

}

privatevoidbutton1_Click(objectsender,rgse)

{

CreateMySplitControls();

}

tabControl

Windows窗体TabControl显示多个选项卡。使用时,先添加一个TabControl

控件,把它拉的足够大。

然后在属性中添加按钮。每个按钮可以控制TabControl的其余页面,作为一

个容器,可以添加其它空间。运行时只要点击按钮,就可以切换选项卡,实现不

同的功能。

StatusBar

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

publicvoidCreateStatusBarPanels()

{

("");

("Two");

("Three");

[0].Width=200;

[0].Text="One";

nels=true;

}

C#(WINFORM)学习

第37页

三、字符和字符串

字符串的操作在程序设计中非常有用,因此单独写成一章。

Char

基本定义

char关键字用于声明一个字符。

char类型的常数可以写成字符、十六进制换码序列或Unicode表示形式。

您也可以显式转换整数字符代码。以下所有语句均声明了一个char变量并用字

符X将其初始化:

charMyChar='X';//Characterliteral

charMyChar='x0058';//Hexadecimal

charMyChar=(char)88;//Castfromintegraltype

charMyChar='u0058';//Unicode

char类型可隐式转换为ushort、int、uint、long、ulong、float、double或

decimal类型。但是,不存在从其他类型到char类型的隐式转换。

ToCharArray

将字符串的部分字符复制到Unicode字符数组。示例

stringstr="012wxyz789";

char[]arr;

arr=Array(3,4);

显示:wxyz

计算字符串宽度

由于英文和中文的显示长度不一样,所以一些场合要区分。

要引用

ization;

C#(WINFORM)学习

第38页

程序为:

//计算一个字符的字符类型,=0汉字,=1英文

privateintgetCharType(charch)

{

inti0;

UnicodeCategoryca1=newUnicodeCategory();

ca1=codeCategory(ch);

switch(ca1)

{

unctuation:

i0=0;//汉字

break;

etter:

i0=0;//汉字

break;

uotePunctuation:

i0=0;//汉字

break;

default:

i0=1;//英文

break;

}

returni0;

}

//计算字符串(ss,包含中文)的实际宽度(返回)、起点(x0)和高度(height)

//输入字号sz,只对于Pixel单位

publicfloatStringWidth(stringss,floatsz,reffloatx0,reffloat

height)

{

charch1;

inti,i0=0;

floatwidth=0;

floatk1=1.02f;//汉字系数

floatk2=0.55f;//英文系数

floatk3=0.15f;//x0系数

floatk4=1.10f;//高度系数

inti1=0;//汉字个数

inti2=0;//英文个数

height=k4*sz;

x0=sz*k3;

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

{

C#(WINFORM)学习

第39页

ch1=(char)ss[i];

i0=getCharType(ch1);

if(i0==0)

i1++;

else

i2++;

}

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

returnwidth;

}

//返回一个point单位的字体的宽度

publicfloatPStringWidth(stringss,floatsz,reffloatx0,reffloat

height)

{

floatwidth=0;

sz=sz*20/15;

width=StringWidth(ss,sz,refx0,refheight);

returnwidth;

}

这个方法在sz(字体大小)5~30内比较准确。很大时有误差。

计算字符串中心

//根据给定点,找到实际标注点,使得以画出的字符串以给定点为中心

PointFStringCenter(strings1,intsz,PointFp0)

{

PointFp1=newPointF();

floatx0=0;

floatheight=0;

floatwidth=StringWidth(s1,sz,refx0,refheight);

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

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

returnp1;

}

计算字符串尺寸示例1—画方框

以下示例利用以上方法,把字符串的长度和高度画成一个方框。

privatevoidbutton2_Click(objectsender,rgse)

{

Graphicsg=Graphics();

SolidBrushmyBrush=newSolidBrush();

floatx0=0;

C#(WINFORM)学习

第40页

floatheight=0;

intsz=10;

floatpx=0,py=50;

PointFp0=newPointF(px,py);

strings1="我们还34fd还是和平使者";

FontmyFont1=newFont("宋体

",sz,,);

floatwidth=StringWidth(s1,sz,refx0,refheight);

ring(s1,myFont1,myBrush,p0);

PointFp1=newPointF(px+x0,py);

PointFp2=newPointF(px+x0+width,py);

PointFp3=newPointF(px+x0+width,py+height);

PointFp4=newPointF(px+x0,py+height);

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

Penpen1=newPen(,2);

lygon(pen1,cur);

}

计算字符串尺寸示例2—找中点

privatevoidbutton1_Click(objectsender,rgse)

{

Graphicsg=Graphics();

SolidBrushmyBrush=newSolidBrush();

PointFps=newPointF();

intsz=10;

PointFp0=newPointF(300,100);

strings1="我们还34fd还是和平使者";

FontmyFont1=newFont("宋体

",sz,,);

ps=StringCenter(s1,sz,p0);

ring(s1,myFont1,myBrush,ps);

//以下画十字线表示中心位置

PointFp1=newPointF(0,p0.Y);

PointFp2=newPointF(600,p0.Y);

PointFp3=newPointF(p0.X,0);

PointFp4=newPointF(p0.X,300);

Penpen1=newPen(,1);

ne(pen1,p1,p2);

ne(pen1,p3,p4);

}

C#(WINFORM)学习

第41页

分行操作

回车符和换行符

“rn”

显示换行的语句为:

="okrn";

+="ok1";

字符串分行

stringmyString1="Thisisthefirstlineofmystring.n"+

"Thisisthesecondlineofmystring.n"+

"Thisisthethirdlineofthestring.n";

stringmyString2=@"Thisisthefirstlineofmystring.

Thisisthesecondlineofmystring.

Thisisthethirdlineofthestring.";

字符串操作

字符串表示

用@后边的字符串不被处理。

A1=@"c:";

strings1=@"c=""";//显示:c=”

strings1=@"c=""""";//显示:c=””

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

求字符串长度

strings1="fdkls我们";

strings2=ng();

(s2);

C#(WINFORM)学习

第42页

运行显示为7,所有字符个数。

裁剪字符串

Strings="123abc456";

ine((3,3));

打印“123456”。

Split方法

标识此实例中的子字符串(它们由数组中指定的一个或多个字符进行分隔),

然后将这些子字符串放入一个String数组中。

简单的例子

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

privatevoidbutton1_Click(objectsender,rgse)

{

stringastring="123,45678,789";

string[]split;

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

split=(chr);

("/"+split[0]+"/");

}

这时可以分成123,456,78,789四个字符串。

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

astring=();

就可以了。

复杂的例子

当存在两个空格时,就出现找出空字符串的错误。用以下方法可以去掉空的

字符串:

string[]Split0(string[]sp)

{

string[]sp1=newstring[];

inti=0,j=0;

foreach(strings1insp)

{

C#(WINFORM)学习

第43页

if(s1!="")

{

sp1[i]=s1;

i=i+1;

}

}

string[]sp2=newstring[i];

for(j=0;j

sp2[j]=sp1[j];

returnsp2;

}

privatevoidbutton1_Click(objectsender,rgse)

{

stringastring="123,45678,789";

string[]split;

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

split=(chr);

split=Split0(split);

("/"+split[0]+"/");

}

C#(WINFORM)学习

第44页

五、文件操作

文件操作

删除

以下均为在控制台应用程序中使用的程序。开始要进行以下三个引用:

usingSystem;

;

;

程序如下:

classTest

{

publicstaticvoidMain()

{

stringpath=@"d:";

if((path))

{

(path);

}

}

}

如果采用相对路径,用

stringsfile=rentDirectory()+@"";

对于在一个.net项目中,默认的路径是在bindebug中,如果要放在项目文

件目录中,用

stringsfile=rentDirectory()+@"....";

生成新文件

可以用:

(path);

或者

FileStreamfs=(path);

C#(WINFORM)学习

第45页

复制

(path,path1,true);

如果最后用false,则第二个文件有时,发生错误。

读写文本文件

usingSystem;

;

privatevoidbutton1_Click(objectsender,rgse)

{

strings1=@"D:";

strings2=@"D:";

Stringinput;

if(!(s1))

{

("Filedoesnotexist.");

return;

}

StreamReadersr=xt(s1);

StreamWriterwr=newStreamWriter(s2);

while((input=ne())!=null)

{

ine(input);

}

("Theend.");

();

();

}

读写中文

strings1=@"d:";

StreamReadersr=newStreamReader(s1,oding("gb2312"));

stringrl;

while((rl=ne())!=null)

{

(rl);

}

();

C#(WINFORM)学习

第46页

文件操作控件

打开文件

用openFileDialog控件。

privatevoidbutton1_Click(objectsender,rgse)

{

OpenFileDialogopenFileDialog1=newOpenFileDialog();

lDirectory=rentDirectory();

="CursorFiles|*.cur";

="SelectaCursorFile";

if(alog()==)

{

Readersr=new

Reader(me);

(End());

();

}

}

选择文件夹

在工具箱上选择folderBrowserDialog:

alog();

strings1=ng()+@"";

StreamWriterwr=newStreamWriter(s1);

C#(WINFORM)学习

第47页

六、绘图

基本绘图

画直线

在Button1中加入以下程序:

en;

myPen=();

csformGraphics=Graphics();

ne(myPen,0,0,200,200);

e();

e();

就可以在Form1上面画一条线了。用

myPen=(,3);

可以改变线的宽度。

最简单的画线程序

Penpen1=newPen(,2);

Graphicsg1=Graphics();

PointFp1=newPointF(0,0);

PointFp2=newPointF(100,100);

ne(pen1,p1,p2);

e();

e();

最后两句可以不写,程序关闭时自动完成。

画椭圆

en;

myPen=();

csformGraphics=Graphics();

lipse(myPen,newRectangle(0,0,200,300));

e();

e();

以下画一个椭圆并填充。

rushmyBrush=rush();

C#(WINFORM)学习

第48页

csformGraphics=Graphics();

lipse(myBrush,newRectangle(0,0,200,300));

e();

e();

以椭圆的中心点画图

//以给定点找画椭圆的原始点,使得椭圆的中心点是给定点

PointFEllipseCenter(intxs,intys,PointFp0)

{

floatek=0.5f;

PointFp1=newPointF();

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

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

returnp1;

}

privatevoidbutton1_Click(objectsender,rgse)

{

Graphicsg=Graphics();

Penpen1=newPen(,1);

Penpen2=newPen(,1);

PointFps=newPointF();

intxs=1,ys=1;//半轴

PointFp0=newPointF(300,100);

ps=EllipseCenter(xs,ys,p0);

//以下画十字线表示中心位置

PointFp1=newPointF(0,p0.Y);

PointFp2=newPointF(600,p0.Y);

PointFp3=newPointF(p0.X,0);

PointFp4=newPointF(p0.X,300);

ne(pen1,p1,p2);

ne(pen1,p3,p4);

lipse(pen2,ps.X,ps.Y,xs,ys);

}

点弧线

en;

myPen=();

csformGraphics=Graphics();

C#(WINFORM)学习

第49页

c(myPen,100,50,140,70,30,180);

e();

e();

多点直线

en;

myPen=();

csformGraphics=Graphics();

PointFpoint1=newPointF(50.0F,50.0F);

PointFpoint2=newPointF(100.0F,25.0F);

PointFpoint3=newPointF(200.0F,5.0F);

PointFpoint4=newPointF(250.0F,50.0F);

PointFpoint5=newPointF(300.0F,100.0F);

PointFpoint6=newPointF(350.0F,200.0F);

PointFpoint7=newPointF(250.0F,250.0F);

PointF[]curvePoints=

{

point1,

point2,

point3,

point4,

point5,

point6,

point7

};

nes(myPen,curvePoints);

e();

e();

C#(WINFORM)学习

第50页

也可以用以下方式给数组赋值:

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

多点弧线

数据同上,修改如下:

intoffset=1;//开始点(从0开始)

intnumSegments=5;//包含后续点数

floattension=1.0F;

rve(myPen,curvePoints,offset,numSegments,tension);

C#(WINFORM)学习

第51页

以下程序可以画一个封闭曲线:

privatevoidbutton1_Click(objectsender,rgse)

{

en;

myPen=();

csformGraphics=Graphics();

PointFpoint1=newPointF(50.0F,50.0F);

PointFpoint2=newPointF(100.0F,25.0F);

PointFpoint3=newPointF(200.0F,5.0F);

PointFpoint4=newPointF(250.0F,50.0F);

PointFpoint5=newPointF(300.0F,100.0F);

PointFpoint6=newPointF(350.0F,200.0F);

PointFpoint7=newPointF(250.0F,250.0F);

PointFpoint8=newPointF(40.0F,150.0F);

PointF[]curvePoints=

{

point1,

point2,

point3,

point4,

point5,

point6,

point7,

point8,

point1

};

intoffset=0;

C#(WINFORM)学习

第52页

intnumSegments=8;

floattension=1.0F;

rve(myPen,curvePoints,offset,numSegments,tension);

//nes(myPen,curvePoints);

e();

e();

}

如果是任意3点(或多点),在起始点不容易圆滑。可以用以下方法画封闭

曲线:

PointF[]curvePoints=

{

point3,

point1,

point2,

point3,

point1

};

intoffset=1;

intnumSegments=3;

floattension=0.5F;

C#(WINFORM)学习

第53页

这样可以保证第一个点处比较圆滑。

参数设置

设置线段宽度:

=3;

在pictrueBox上面画线,修改this:

csformGraphics=Graphics();

填充

rushmyBrush=new

rush(ink);

en;

myPen=(,1);

csformGraphics=Graphics();

PointFpoint1=newPointF(50.0F,50.0F);

PointFpoint2=newPointF(100.0F,25.0F);

PointFpoint3=newPointF(200.0F,5.0F);

PointFpoint4=newPointF(250.0F,50.0F);

PointFpoint5=newPointF(300.0F,100.0F);

PointFpoint6=newPointF(350.0F,200.0F);

PointFpoint7=newPointF(250.0F,250.0F);

PointF[]curvePoints=

{

C#(WINFORM)学习

第54页

point1,

point2,

point3,

point4,

point5,

point6,

point7

};

lygon(myBrush,curvePoints);

lygon(myPen,curvePoints);

e();

e();

e();

颜色

颜色基本设置

普通颜色设置可以直接选取系统定义的颜色。高级设置采用RGB颜色。

ColormyColor;

myColor=gb(23,56,78);

每个数字均必须是从0到255之间的一个整数,分别表示红、绿、蓝三种

原色。其中0表示没有该颜色,而255则为所指定颜色的完整饱和度。如

gb(0,255,0)表示绿色,gb(255,255,0)表示黄色,

gb(0,0,0)呈现为黑色,而gb(255,255,255)呈现为白

色。

还可以设置透明度,如

ColormyColor;

myColor=gb(127,23,56,78);

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

选择颜色

以下程序可以从调色板选择一个颜色,在textBox上面显示。

privatevoidbutton1_Click(objectsender,rgse)

{

ColorDialogMyDialog=newColorDialog();

C#(WINFORM)学习

第55页

ullOpen=false;

lp=true;

=lor;

if(alog()==)

lor=;

}

产生窗体选择颜色

本程序在一个菜单里调用选择程序,产生一个动态的窗体,选择颜色后返回

主程序,刷新原来的页面。

由于没有掌握控制动态控件集合的方法,只好用枚举的方法定义动态控件,

对于多于10个的颜色序列,需要修改程序。

Formform1;

boolCform=true;

//颜色设置

privatevoidmenuItem31_Click(objectsender,rgse)

{

while(Cform)

{

CreateColorForm();

Tuli1();

DisLine();

}

Cform=true;

}

//产生颜色输入窗体

privatevoidCreateColorForm()

{

inti;

form1=newForm();

Button[]ColorButton=newButton[];

Label[]ColorLabel=newLabel[];

Buttonbutton0=newButton();

=130;

=130+*30;

="等值线颜色输入";

rderStyle=ialog;

C#(WINFORM)学习

第56页

lBox=false;

osition=Screen;

="退出";

=80;

on=newPoint(25,50+*30);

(button0);

Button=button0;

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

{

ColorLabel[i]=newLabel();

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

ColorLabel[i].Width=30;

ColorLabel[i].Text=1[i].ToString();

(ColorLabel[i]);

ColorButton[i]=newButton();

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

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

ColorButton[i].Width=30;

switch(i)

{

case0:

ColorButton[i].Click+=andler(ColorButton0_Click);

break;

case1:

ColorButton[i].Click+=andler(ColorButton1_Click);

break;

case2:

ColorButton[i].Click+=andler(ColorButton2_Click);

break;

case3:

ColorButton[i].Click+=andler(ColorButton3_Click);

break;

case4:

ColorButton[i].Click+=andler(ColorButton4_Click);

break;

case5:

ColorButton[i].Click+=andler(ColorButton5_Click);

break;

case6:

ColorButton[i].Click+=andler(ColorButton6_Click);

break;

C#(WINFORM)学习

第57页

case7:

ColorButton[i].Click+=andler(ColorButton7_Click);

break;

case8:

ColorButton[i].Click+=andler(ColorButton8_Click);

break;

case9:

ColorButton[i].Click+=andler(ColorButton9_Click);

break;

case10:

ColorButton[i].Click+=andler(ColorButton10_Click);

break;

default:

break;

}

(ColorButton[i]);

}

+=andler(button0_Click);

alog();

}

privatevoidColorSelect(intsi)

{

ColorDialogMyDialog=newColorDialog();

ullOpen=true;

lp=true;

=cColor[si];

if(alog()==)

cColor[si]=;

e();

}

privatevoidColorButton0_Click(objectsender,rgse)

{ColorSelect(0);}

privatevoidColorButton1_Click(objectsender,rgse)

{ColorSelect(1);}

privatevoidColorButton2_Click(objectsender,rgse)

{ColorSelect(2);}

privatevoidColorButton3_Click(objectsender,rgse)

{ColorSelect(3);}

privatevoidColorButton4_Click(objectsender,rgse)

{ColorSelect(4);}

privatevoidColorButton5_Click(objectsender,rgse)

{ColorSelect(5);}

C#(WINFORM)学习

第58页

privatevoidColorButton6_Click(objectsender,rgse)

{ColorSelect(6);}

privatevoidColorButton7_Click(objectsender,rgse)

{ColorSelect(7);}

privatevoidColorButton8_Click(objectsender,rgse)

{ColorSelect(8);}

privatevoidColorButton9_Click(objectsender,rgse)

{ColorSelect(9);}

privatevoidColorButton10_Click(objectsender,rgse)

{ColorSelect(10);}

privatevoidbutton0_Click(objectsender,rgse)

{

Cform=false;

e();

}

Font和标注

基本操作

可以在指定的点开始写字,也可以在一个范围(如矩形)内写字。

FontmyFont=newFont("TimesNewRoman",14);

Graphicsg=Graphics();

PenmyPen=newPen();

rushmyBrush=newSolidBrush();

ctangle(myPen,10,10,100,200);

ring("Lookatthistext!",myFont,myBrush,newRectangleF(10,10,100,200));

ring("Lookatthistext!",myFont,myBrush,10,250);

画点和标注

en;

myPen=(,1);

csformGraphics=Graphics();

rushdrawBrush=new

rush();

awFont=("Arial",8);

stringdrawString="201";

floatx=100.0f;

C#(WINFORM)学习

第59页

floaty=100.0f;

lipse(myPen,x,y,4,4);

ring(drawString,drawFont,drawBrush,x,y);

e();

e();

e();

e();

Font定义

publicFont(

FontFamilyfamily,

floatemSize,

FontStylestyle,

GraphicsUnitunit

);

以下的例子可以改变字体,大小、字形、单位,还可以设置成垂直。

//FontmyFont=newFont("TimesNewRoman",14,,eter);

FontmyFont=newFont("隶书",34,ine,);

Graphicsg=Graphics();

rushmyBrush=newSolidBrush();

FormatdrawFormat=Format

(ionVertical);

ring("Hello!你好",myFont,myBrush,10,10,drawFormat);

根据给定点找到实际标注点

//根据给定点,找到实际标注点,使得以画出的字符串以给定点为中心

publicPointFStringCenter(strings1,floatsz,PointFp0)

{

PointFp1=newPointF();

floatx0=0;

floatheight=0;

floatwidth=StringWidth(s1,sz,refx0,refheight);

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

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

returnp1;

}

C#(WINFORM)学习

第60页

pictureBox

用pictureBox画图

和在form上面画图类似,只是把this替换成pictureBox1:

en;

myPen=(,1);

csformGraphics=Graphics();

rushdrawBrush=new

rush();

awFont=("Arial",8);

stringdrawString="201";

floatx=200.0f;

floaty=100.0f;

lipse(myPen,x,y,4,4);

ring(drawString,drawFont,drawBrush,x,y);

e();

e();

e();

e();

用pictureBox显示一个图片

有固定模式和缩放模式,通过设置SizeMode实现。程序如下:

de=hImage;//按图像文件大小缩放

//=le("");//文件放在binDebug文件夹

=le(@"....");//文件放在程序文件夹

Region

基本概念

指示由矩形和由路径构成的图形形状的内部。

基本操作

cse=Graphics();

C#(WINFORM)学习

第61页

RectangleregionRect=newRectangle(20,20,100,100);

ctangle(,regionRect);

RectangleFcomplementRect=newRectangleF(90,30,100,100);

ctangle(,(complementRect));

RegionmyRegion=newRegion(regionRect);

ect(complementRect);

SolidBrushmyBrush=newSolidBrush();

gion(myBrush,myRegion);

主要图形操作还有Union和Xor。

Polygon的镂空

采用异或(Xor)运算。需要把polygon转换成路径:

Graphicsg1=Graphics();

GraphicsPathmyPath1=newGraphicsPath();

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

,newPointF(100,100),newPointF(90,150),newPointF(10,70)};

ygon(pts);

th(,myPath1);

GraphicsPathmyPath2=newGraphicsPath();

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

,newPointF(100,40)};

ygon(pts1);

th(,myPath2);

RegionmyRegion=newRegion(myPath1);

(myPath2);

SolidBrushmyBrush=newSolidBrush();

gion(myBrush,myRegion);

如果要镂空多个空洞,需要把这些空洞都加入到myPath2中,其余操作同样。

采用交、并和异或运算,都可以把两个对象互换。

显示数据

publicvoidDisplayRegionData(Graphicse,intlen,RegionDatadat)

{

inti;

floatx=20,y=140;

C#(WINFORM)学习

第62页

FontmyFont=newFont("Arial",8);

SolidBrushmyBrush=newSolidBrush();

ring("myRegionData=",myFont,myBrush,newPointF(x,y));

y=160;

for(i=0;i

{

if(x>300)

{

y+=20;

x=20;

}

ring([i].ToString(),myFont,myBrush,newPointF(x,y));

x+=30;

}

}

路径

基本应用

用GraphicsPath可以把各种绘图元素(包括文字)包含进来,最后用DrawPath

画出来。

需要:g2D;

privatevoidbutton2_Click(objectsender,rgse)

{

PenmyPen=newPen(,1);

csformGraphics=Graphics();

GraphicsPathmyPath1=newGraphicsPath();

e(0,0,10,20);

ipse(20,20,10,10);

e(40,40,50,120);

th(myPen,myPath1);

e();

e();

e();

}

C#(WINFORM)学习

第63页

不连续线条

用一个半径为0的点加在中间:

e(0,0,10,20);

ipse(20,20,0,0);

e(40,40,50,120);

也可以用两个path,然后用

h(path3,false);

复杂应用

路径可以包含其它路径,汇总成一个大的图形。

还可以通过矩阵变换进行缩放、平移和旋转。

简单Matrix变换

可以通过矩阵变换进行图形的变换。

privatevoidbutton1_Click(objectsender,rgse)

{

cse1=Graphics();

PenmyPen=newPen(,1);

PenmyPen2=newPen(,1);

MatrixmyMatrix1=newMatrix(1.0f,0.0f,0.0f,3.0f,0.0f,0.0f);//x和y方向都

放大3倍

//MatrixmyMatrix1=newMatrix(1.0f,0.0f,0.0f,1.0f,50.0f,50.0f);//平移50,50

ctangle(myPen,0,0,100,100);

orm=myMatrix1;

ctangle(myPen2,0,0,100,100);

e();

e();

}

复杂Matrix变换

下例显示缩放、旋转和移动变换。

publicvoidMultiplyExample(PaintEventArgse)

{

PenmyPen=newPen(,2);

PenmyPen2=newPen(,1);

C#(WINFORM)学习

第64页

MatrixmyMatrix1=newMatrix(3.0f,0.0f,0.0f,3.0f,0.0f,0.0f);//Scale

MatrixmyMatrix2=newMatrix(0.0f,1.0f,-1.0f,0.0f,0.0f,0.0f);//Rotate90,

MatrixmyMatrix3=newMatrix(1.0f,0.0f,0.0f,1.0f,250.0f,50.0f);//Translate

ListMatrixElements(e,myMatrix1,"BeginningMatrix",6,40);

ly(myMatrix2,);

ListMatrixElements(e,myMatrix1,"MatrixAfter1stMultiplication",6,60);

ly(myMatrix3,);

ListMatrixElements(e,myMatrix1,"MatrixAfter2ndMultiplication",6,80);

ctangle(myPen,0,0,100,100);

orm=myMatrix1;

ctangle(myPen2,0,0,100,100);

}

publicvoidListMatrixElements(PaintEventArgse,Matrixmatrix,stringmatrixName,

intnumElements,inty)

{

inti;

floatx=20,X=200;

FontmyFont=newFont("Arial",8);

SolidBrushmyBrush=newSolidBrush();

ring(matrixName+":",myFont,myBrush,x,y);

for(i=0;i

{

ring(ts[i].ToString()+",

",myFont,myBrush,X,y);

X+=30;

}

}

解决放大线条变宽问题

放大后的线条全部变宽,无法应用于GIS变换。对于多个线条组成的图形需

要缩放和平移时,可以重新生成一个点集(其中自己加上缩放和平移计算)来做。

从路径转换到点集用PathPoints属性。

C#(WINFORM)学习

第65页

Image

简单保存

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

publicclassForm1:

{

button1;

button2;

eBoxpictureBox1;

privateImagecuurimage;

然后在程序中引用即可。

cuurimage=;

("");

利用动态Image画图

PointFp1=newPointF();

PointFp2=newPointF();

PenmyPen=newPen(,1);

cuurimage=le("");

Graphicsg=age(cuurimage);

Color[]c={ink,,,,};

for(k=0;k<=-1;k++)

{

=c[(int)LineColor[k]];

p1=(PointF)LineArray[i];

i++;

p2=(PointF)LineArray[i];

i++;

ne(myPen,p1,p2);

}

e();

g=CreateGraphics();

age(cuurimage,50,0,+100,+10);

e();

C#(WINFORM)学习

第66页

画图保存

在一个pictureBox上保存所画图像。

先需要加载一个背景图片,把图画在这个图片上,最后保存到另外一个文件

中。

privateImagecuurimage;

privatevoidbutton2_Click(objectsender,rgse)

{

PenmyPen=newPen(,2);

=le(@"....");

cuurimage=;

Graphicsg=age(cuurimage);

lipse(myPen,100,100,44,14);

("");

e();

e();

}

利用Image擦除图像

下例要先准备一个jpg图像文件。

先把jpg文件放在pictureBox的Graphics类g1上,然后在其上画图,保存

在一个image类的变量中。需要擦除的图形画在另外一个Graphics类g2上,然

后在g1上用DrawImage方法,就可以把g2上的图形全部擦除。

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

ImageimgBack;

csg1,g2;

PenPen1;

//新图形

privatevoidbutton1_Click(objectsender,rgse)

{

g2=Graphics();

Pen1=newPen(,2);

ne(Pen1,10,10,200,200);

//h();

}

//原始图形

privatevoidbutton2_Click(objectsender,rgse)

{

C#(WINFORM)学习

第67页

=le(@"");

imgBack=;

g1=age();

Pen1=newPen(,2);

ne(Pen1,10,100,200,20);

//h();

}

//擦除

privatevoidbutton3_Click(objectsender,rgse)

{

age(imgBack,0,0);

h();

}

图形其它

找到一个点

以下程序可以找到一个存在的点,并在鼠标移动时改变光标和提示。点击显

示其它信息。

PointFPt1=newPointF();

PointFPt2=newPointF();

csg;

intkk1=0;//判断是否重画,=1为已经重画

intkk2=0;//判断在距离内,=1为在距离内

doublejl0=5;//距离

privatestaticfloatDistance(PointFp1,PointFp2)

{

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

}

privatevoidForm1_Closed(objectsender,rgse)

{

e();

}

privatevoidForm1_MouseDown(objectsender,ventArgse)

{

if(kk2==1)

("xianshi");

C#(WINFORM)学习

第68页

}

privatevoidForm1_MouseMove(objectsender,ventArgse)

{

doublejl1;

Pt2.X=e.X;

Pt2.Y=e.Y;

jl1=Distance(Pt1,Pt2);

if(jl1

{

=;

();

=(int)Pt1.X-6;

=(int)Pt1.Y-20;

="x="+ng()+"y="+ng();

=*7;

=15;

kk2=1;//找到图像

kk1=0;//没有显示图像

}

else

{

if(kk1==0)

{

=;

kk2=0;

();

lipse(newSolidBrush(),Pt1.X,Pt1.Y,5,5);//重新显示

kk1=1;

}

}

}

privatevoidbutton2_Click(objectsender,rgse)

{

Pt1.X=100;

Pt1.Y=100;

lipse(newSolidBrush(),Pt1.X,Pt1.Y,5,5);

}

privatevoidForm1_Load(objectsender,rgse)

{

g=Graphics();

();

C#(WINFORM)学习

第69页

}

拖动一个点

可以实现发现点时改变鼠标光标和显示坐标提示,拖动鼠标完成点的移动。

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

PointFPt1=newPointF();

PointFPt2=newPointF();

csg;

intkk1=0;//判断是否拖动,=1为拖动

intkk2=0;//判断在距离内,=1为在距离内

doublejl0=5;//距离

privatestaticfloatDistance(PointFp1,PointFp2)

{

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

}

privatevoidForm1_Closed(objectsender,rgse)

{

e();

}

privatevoidForm1_MouseUp(objectsender,ventArgse)

{

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

{

Pt2.X=e.X;

Pt2.Y=e.Y;

lipse(newSolidBrush(lor),Pt1.X,Pt1.Y,5,5);//删除原

来的点

lipse(newSolidBrush(),Pt2.X,Pt2.Y,5,5);//画新的

Pt1=Pt2;

=;

kk1=0;

kk2=0;

();

}

=;

}

C#(WINFORM)学习

第70页

privatevoidForm1_Load(objectsender,rgse)

{

g=Graphics();

();

}

privatevoidForm1_MouseDown(objectsender,ventArgse)

{

if(kk2==1)

kk1=1;

else

kk1=0;

}

privatevoidForm1_MouseMove(objectsender,ventArgse)

{

doublejl1;

Pt2.X=e.X;

Pt2.Y=e.Y;

jl1=Distance(Pt1,Pt2);

if(jl1

{

=;

();

=(int)Pt2.X-6;

=(int)Pt2.Y-20;

="x="+ng()+"y="+ng();

kk2=1;

}

elseif(kk1==0)

{

=;

kk2=0;

();

}

}

privatevoidbutton1_Click(objectsender,rgse)

{

Pt1.X=100;

Pt1.Y=100;

lipse(newSolidBrush(),Pt1.X,Pt1.Y,5,5);

}

C#(WINFORM)学习

第71页

拖动一个方框

PointFp1=newPointF();

PointFp2=newPointF();

en;

en1;

en2;

csg1;

intdl;

privatevoidForm1_MouseDown(objectsender,ventArgse)

{

p1.X=e.X;

p1.Y=e.Y;

dl=1;

}

privatevoidForm1_MouseUp(objectsender,ventArgse)

{

p2.X=e.X;

p2.Y=e.Y;

ctangle(myPen,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

dl=0;

}

privatevoidForm1_Load(objectsender,rgse)

{

myPen=(,2);

myPen1=(,1);

myPen2=(lor,1);

g1=Graphics();

dl=0;

}

privatevoidForm1_Closed(objectsender,rgse)

{

e();

e();

e();

e();

}

privatevoidForm1_MouseMove(objectsender,ventArgse)

{

C#(WINFORM)学习

第72页

if(dl==1)

{

ctangle(myPen2,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

p2.X=e.X;

p2.Y=e.Y;

ctangle(myPen1,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

}

}

动态画方框

PointFp1=newPointF();

PointFp2=newPointF();

en;

en1;

en2;

csg1;

intdl;

privatevoidForm1_MouseDown(objectsender,ventArgse)

{

p1.X=e.X;

p1.Y=e.Y;

dl=1;

}

privatevoidForm1_MouseUp(objectsender,ventArgse)

{

p2.X=e.X;

p2.Y=e.Y;

ctangle(myPen,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

dl=0;

}

privatevoidForm1_Load(objectsender,rgse)

{

myPen=(,2);

myPen1=(,1);

myPen2=(lor,1);

g1=Graphics();

dl=0;

}

privatevoidForm1_Closed(objectsender,rgse)

C#(WINFORM)学习

第73页

{

e();

e();

e();

e();

}

privatevoidForm1_MouseMove(objectsender,ventArgse)

{

if(dl==1)

{

ctangle(myPen2,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

p2.X=e.X;

p2.Y=e.Y;

ctangle(myPen1,p1.X,p1.Y,p2.X-p1.X,p2.Y-p1.Y);

}

}

读取等值线文件画图

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

staticvoidMain()

{

(newForm1());

}

publicstringss1;

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

stringQu1()

{

inti=0;

boolcbl=true;

intls=;

while((i

{

charc1=ss1[i];

strings1=ng(c1);

if((""))

cbl=false;

i++;

}

C#(WINFORM)学习

第74页

strings2=(i,ls-i);

ss1=(0,i-1);

//("ss1="+ss1);

returns2;

}

privatevoidbutton1_Click(objectsender,rgse)

{

stringsfile=@"D:";

Strings0,s1;

inti,j,k;

floatx1,y1;

boolBl=true;

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

if(!(sfile))

{

("Filedoesnotexist.");

return;

}

//画线设置

en;

floatk1=0.08F;

floatk2=0.08F;

floatx0=0;

floaty0=0;

myPen=();

=1;

csformGraphics=Graphics();

StreamReadersr=xt(sfile);

s0=ne();

s0=ne();

s0=ne();

//读取数值文件

k=0;

s0=ne();

ss1=();

while(s0!=null)

{

i=0;

while(Bl)

C#(WINFORM)学习

第75页

{

s1=Qu1();

x1=le(s1);

ss1=();

s1=Qu1();

y1=le(s1);

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

i++;

s0=ne();

ss1=();

if(("-1"))

Bl=false;

}

Bl=true;

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

for(j=0;j

{

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

}

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

k++;

//画线

nes(myPen,cPoints);

s0=ne();

if(s0!=null)

ss1=();

}

e();

e();

();

}

格式:

0.000.008895.008895.00

25282929.530.5313235

5644.204625.4032.00

5633.504641.5732.00

5628.854655.0532.00

5633.504681.3532.00

5634.674684.7032.00

5663.154703.2732.00

C#(WINFORM)学习

第76页

5692.804700.7032.00

5714.984684.7032.00

5722.454668.6832.00

5726.264655.0532.00

5722.454640.6632.00

5714.234625.4032.00

5692.804612.0732.00

5663.154613.0332.00

5644.204625.4032.00

5644.204625.4032.00

-1

2463.288895.0025.00

2487.038865.3525.00

2490.608860.8625.00

……

C#(WINFORM)学习

第77页

十、其它常用方法

时间处理

间隔计算

DateTimeoldDate=newDateTime(2002,7,15);

DateTimenewDate=;

//Differenceindays,hours,andminutes.

TimeSpants=newDate-oldDate;

//Differenceindays.

intdifferenceInDays=;

ine("Differenceindays:{0}",differenceInDays);

注意,TimeSpan是系统基础类。

利用时间判断

publicstaticboolJM(DateTimeT0,intii)

{

boolBl=false;

DateTimeT1=;

TimeSpants=T1-T0;

if(>ii)

Bl=true;

returnBl;

}

DateTimeoldDate=newDateTime(2007,1,29);//起始时间

if((oldDate,100))//有效期100天

{

("试用版到期,请和北京派得伟业公司联系,电话************");

();

}

C#(WINFORM)学习

第78页

Timer类

以下程序在每隔2秒显示一个MessageBox提示。其中TimerEventProcessor

方法在timer开始后就自动运行。

yTimer=();

staticintalarmCounter=1;

staticboolexitFlag=false;

privatestaticvoidTimerEventProcessor(ObjectmyObject,EventArgsmyEventArgs)

{

();

if(("继续?","计

数:"+alarmCounter,)==)

{

alarmCounter+=1;

d=true;

}

else

exitFlag=true;

}

privatevoidbutton1_Click(objectsender,rgse)

{

+=newEventHandler(TimerEventProcessor);

al=2000;

();

while(exitFlag==false)

{

//Processesalltheeventsinthequeue.

ts();

}

}

延时程序

以下为延时程序,单位为毫秒。由于econds数值在大于1000时出错,

所以要转换成s。

publicvoidTimeDelay(intit)

{

boolBl=true;

DateTimeT1,T0;

TimeSpants;

C#(WINFORM)学习

第79页

intit0;

T0=;

while(Bl)

{

T1=;

ts=T1-T0;

if(it>1000)

{

it0=32(it/1000);

if(s>it0)

Bl=false;

}

else

if(econds>it)

Bl=false;

ts();

}

}

privatevoidbutton1_Click(objectsender,rgse)

{

("开始");

TimeDelay(2900);

("时间到。");

}

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

dll文件调用

基本概念

动态链接库(DLL)在运行时链接到程序。本程序通过两个cs文件生成一个

的库文件。

:为源文件,其中包含Add(longi,longj)方法。该方法返回参

数之和。包含Add方法的AddClass类是命名空间MyMethods的成员。

:为源文件,其中包含Multiply(longx,longy)方法。该方法

返回参数之积。包含Multiply方法的MultiplyClass类也是命名空间

MyMethods的成员。

C#(WINFORM)学习

第80页

:包含Main方法的文件。它使用DLL文件中的方法来计算运

行时参数的和与积。

源程序

文件:

//Addtwonumbers

usingSystem;

namespaceMyMethods

{

publicclassAddClass

{

publicstaticlongAdd(longi,longj)

{

return(i+j);

}

}

}

文件:

//Multiplytwonumbers

usingSystem;

namespaceMyMethods

{

publicclassMultiplyClass

{

publicstaticlongMultiply(longx,longy)

{

return(x*y);

}

}

}

C#(WINFORM)学习

第81页

文件:

//CallingmethodsfromaDLLfile

usingSystem;

usingMyMethods;

classMyClient

{

publicstaticvoidMain(string[]args)

{

ine(":");

if(!=2)

{

ine("Usage:MyClient");

return;

}

longnum1=(args[0]);

longnum2=(args[1]);

longsum=(num1,num2);

longproduct=ly(num1,num2);

ine("Thesumof{0}and{1}is{2}",

num1,num2,sum);

ine("Theproductof{0}and{1}is{2}",

num1,num2,product);

}

}

此文件包含使用DLL方法Add和Multiply的算法。它首先分析从命令行

输入的参数num1和num2。然后使用AddClass类中的Add方法计算和,使用

MultiplyClass类中的Multiply方法计算积。

请注意,文件开头的using指令使您得以在编译时使用未限定的类名来引

用DLL方法,例如:

C#(WINFORM)学习

第82页

ly(num1,num2);

否则,必须使用完全限定名,例如:

ly(num1,num2);

编译

若要生成文件,使用以下命令行编译文件和文件

csc/target:library/out:

如果对于一个文件以及缺省dll文件名,可以用:

csc/target:

这样生成一个的文件。

若要生成可执行文件,请使用以下命令行:

csc/out:/reference:

使用命令行编译文件,在【开始】/【程序】/【

2003】/【工具】/【命令提示】。

默认目录为当前用户目录。如果你使用Administrator,则目录为

C:DocumentsandSettingsAdministrator。你可以把几个cs文件拷贝到这个

目录中。

执行

若要运行程序,请输入EXE文件的名称,文件名的后面跟两个数字,例如:

MyClient12345678

运行结果为:

:

Thesumof1234and5678is6912

Theproductof1234and5678is7006652

自动编译dll

建立一个bat文件如下:

c:/target:library

C#(WINFORM)学习

第83页

就可以自动把编译成了。

在IDE中调用dll

把以上的文件编译成后,在一个控制台应用程序中使用

。先引用,然后修改程序为:

usingSystem;

usingMyMethods;

classMyClient

{

publicstaticvoidMain(string[]args)

{

ine(":");

longnum1=100;

longnum2=550;

longsum=(num1,num2);

longproduct=ly(num1,num2);

ine("Thesumof{0}and{1}is{2}",

num1,num2,sum);

ine("Theproductof{0}and{1}is{2}",

num1,num2,product);

}

}

运行结果和以前一样。

在C#中调用dll

1.编译dll文件。

2.把dll文件拷贝到工作文件夹下面。

3.在右边文件夹的【引用】上右击,选择【添加引用】,在【com】中浏览

选择,即可添加。也可以在菜单【项目】/【添加引用】上添加。

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

C#(WINFORM)学习

第84页

创建自定义控件

定义控件类

定义从l派生的类。

publicclassFirstControl:Control{...}

定义属性

以下代码片段定义名为TextAlignment的属性,FirstControl使用该属性来

定义从Control继承的Text属性的显示格式。

//g

//namespacethatspecifiesthealignmentofcontentonadrawing

//surface.

privateContentAlignmentalignment=Left;

publicContentAlignmentTextAlignment{

get{

returnalignment;

}

set{

alignment=value;

//TheInvalidatemethodinvokestheOnPaintmethoddescribed

//instep3.

Invalidate();

}

}

在设置更改控件外观显示的属性时,必须调用Invalidate方法来重新绘制该

控件。Invalidate是在基类Control中定义的。

C#(WINFORM)学习

第85页

重写OnPaint方法

重写从Control继承的受保护的OnPaint方法,以便为控件提供呈现逻辑。

如果不改写OnPaint,您的控件将无法自行绘制。在下列代码片段中,OnPaint方

法显示了从Control继承的具有默认对齐方式的Text属性。

publicclassFirstControl:Control{

publicFirstControl(){...}

protectedoverridevoidOnPaint(PaintEventArgse){

t(e);

ring(Text,Font,newSolidBrush(ForeColor),

ClientRectangle,style);

}

}

提供控件属性

属性可使可视化设计器在设计时适当地显示控件及其属性和事件。以下代码

片段将属性应用于TextAlignment属性。在这样的

设计器中,Category属性(如代码片段所示)使该属性显示在逻辑类别中。在

选择TextAlignment属性时,Description属性使说明字符串显示在“属性”窗

口的底部。

[

Category("Alignment"),

Description("Specifiesthealignmentoftext.")

]

publicContentAlignmentTextAlignment{...}

提供控件资源

通过使用编辑器选项(C#中为/res),可以为控件提供诸如位图之类的资源

来打包控件的资源。在运行时,使用ceManager类的方

法可检索该资源。有关创建和使用资源的更多信息,请参见.NET示例–如

C#(WINFORM)学习

第86页

何获取:资源快速入门。

编译和部署控件

要编译和部署FirstControl,请执行以下步骤:

将下列示例中的代码保存到源文件(如)。

将源代码编译成程序集,并将其保存到应用程序的目录中。为了实现这一目

的,需在包含源文件的目录中执行以下命令。

csc/t:library/out:[pathtoyourapplication'sdirectory]/

/r:/r:/r:

/t:library编译器选项告诉编译器正在创建的程序集是一个库(而不是一个可

执行程序)。/out选项用来指定程序集的路径和名称。/r选项提供代码所参考的

程序集的名称。在本示例中,创建了一个仅供您自己的应用程序使用的专用程序

集。因此,您必须将其保存到您的应用程序的目录中。有关打包和部署控件进行

分发的更多信息,请参见部署.NETFramework应用程序。

示例程序

以下示例显示了FirstControl的代码。该控件包含在命名空间

CustomWinControls中。命名空间提供了相关类型的逻辑分组。可以在新命名空

间或现有的命名空间中创建控件。在C#中,using声明(在VisualBasic中,

Imports)允许从命名空间访问类型,而无须使用完全限定的类型名称。在以下示

例中,using声明允许代码从作为简单控件存取Control

类,而无须使用完全限定的名称l。

namespaceCustomWinControls{

usingSystem;

entModel;

;

g;

publicclassFirstControl:Control{

privateContentAlignmentalignment=Left;

C#(WINFORM)学习

第87页

[

Category("Alignment"),

Description("Specifiesthealignmentoftext.")

]

publicContentAlignmentTextAlignment{

get{

returnalignment;

}

set{

alignment=value;

//TheInvalidatemethodinvokestheOnPaintmethod.

Invalidate();

}

}

//OnPaintalignstext,asspecifiedbythe

//TextAlignmentproperty,bypassingaparameter

//csobject.

protectedoverridevoidOnPaint(PaintEventArgse){

t(e);

StringFormatstyle=newStringFormat();

ent=;

switch(alignment){

Left:

ent=;

break;

Right:

ent=;

break;

Center:

C#(WINFORM)学习

第88页

ent=;

break;

}

//gclasstowrite

//dClientRectanglearepropertiesinheritedfrom

//Control.

ring(Text,Font,newSolidBrush(ForeColor),

ClientRectangle,style);

}

}

}

在窗体上使用自定义控件

以下示例说明了一个使用FirstControl的简单窗体。它创建了三个

FirstControl实例,每个实例都有不同的TextAlignment属性值。

将下列示例中的代码保存到源文件()。

通过从包含该源文件的目录中执行以下命令,将源代码编译成可执行的程序

集。

csc/r:/r:/r:

/r:

是包含类FirstControl的程序集。该程序集必须与存

取它的窗体源文件位于同一目录中(或)。

使用下列命令执行。

SimpleForm

usingSystem;

;

g;

usingCustomWinControls;

classSimpleForm:Form{

C#(WINFORM)学习

第89页

privateFirstControlleft;

privateFirstControlcenter;

privateFirstControlright;

protectedoverridevoidDispose(booldisposing){

e(disposing);

}

publicSimpleForm():base(){

left=newFirstControl();

="Left";

on=newPoint(50,50);

=newSize(50,50);

(left);

center=newFirstControl();

ignment=Center;

="Center";

on=newPoint(125,50);

=newSize(50,50);

(center);

right=newFirstControl();

ignment=Right;

="Right";

on=newPoint(200,50);

=newSize(50,50);

(right);

}

C#(WINFORM)学习

第90页

[STAThread]

publicstaticvoidMain(string[]args){

Formform=newSimpleForm();

="UsesFirstControl";

=newSize(400,150);

(form);

}

}

用户控件

用途

用户控件相当于带界面的类模块,并可以编译成dll。具有以下优点:

1.可以把程序分离成内核部分和引用部分,便于开发和维护;

2.可以多进程调用;

3.安全性好。

自己创建的例子

自己创建一个简单用户控件的步骤为:

1.新建一个“Windows控件库”的项目;

2.编写控件程序,如需要传递参数,定义如下:

publicPointFp1,p2;

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

4.用【文件】/【添加项目】/【新建项目】,新建一个使用控件项目,为“Windows

应用程序”;

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

6.在【工具箱】/【我的用户控件】中选择生成的控件;

7.把使用项目设置为启动;

8.编写程序。如果传递参数,用:

privatevoidForm1_Load(objectsender,rgse)

C#(WINFORM)学习

第91页

{

userControl11.p1=newPointF(20,20);

userControl11.p2=newPointF(100,200);

}

然后可以在这个解决方案中随意修改控件设计,只要运行调用程序,就可以

自动编译和加载控件了。如果修改了控件的界面,还需要重新生成和加载。

如果在单独的使用程序中调用这个dll控件,则先需要添加引用,然后需要

在“工具箱”上点击右键,选择【添加/移除项】,把这个控件添加到工具箱上,

才可以添加到form上。

在使用程序中可以随意调用控件中的方法。如果要在控件中调用使用程序中

的方法,则可以使用一个传递参数,如intbi,每次点击事件时bi值改变。然后

在使用程序中用一个timer控件,用事件timer1_Tick来监控bi的变化,来触发一

个方法。

inputBox方法

类定义

publicclassInputBox:

{

xtxtData;

blInfo;

nercomponents=null;

privateInputBox()

{

InitializeComponent();

}

protectedoverridevoidDispose(booldisposing)

{

if(disposing)

{

if(components!=null)

{

e();

}

}

e(disposing);

C#(WINFORM)学习

第92页

}

privatevoidInitializeComponent()

{

a=x();

o=();

dLayout();

//txtData

=("宋体",10.5F,

r,,(()(134)));

on=(19,8);

="txtData";

=(317,23);

ex=0;

="";

n+=new

ntHandler(a_KeyDown);

//lblInfo

=("宋体",9F,

r,,(()(134)));

on=(19,32);

="lblInfo";

=(317,16);

ex=1;

="按[Enter]键确认,按[Esc]键取消";

//InputBox

aleBaseSize=(6,14);

Size=(350,48);

lBox=false;

(o);

(a);

rderStyle=ialog;

="InputBox";

="InputBox";

Layout(false);

}

//对键盘进行响应

privatevoidtxtData_KeyDown(objectsender,ntArgse)

{

if(e==)

C#(WINFORM)学习

第93页

{

();

}

elseif(e==)

{

=;

();

}

}

//显示InputBox

publicstaticstringShowInputBox(stringTitle,stringkeyInfo)

{

InputBoxinputbox=newInputBox();

=Title;

if(()!=)

=keyInfo;

alog();

;

}

}

普通调用

privatevoidbutton1_Click(objectsender,rgse)

{

stringinMsg=putBox("输入信息",);

//对用户的输入信息进行检查

if(()!=)

{

(inMsg);

}

else

{

("输入为空!");

}

如果需要输入一个int数值,则程序如下:

stringinMsg=putBox("输入信息",);

inta1;

if(()!=)

{

try

{

a1=32(());

C#(WINFORM)学习

第94页

(ng());

}

catch(Exception)

{

("输入错误!继续保持原有数据。");

}

}

else

{

("输入为空!");

}

增加缺省值

在类中增加以下程序:

publicstaticstringShowInputBox(stringTitle,stringkeyInfo,stringtextInfo)

{

InputBoxinputbox=newInputBox();

=Title;

=textInfo;

if(()!=)

=keyInfo;

alog();

;

}

可以在调用时输入textBox中的缺省值。

版本设置

在文件中修改

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

则在最后生成的EXE文件中显示版本号2.2.1.10803,最后一个号码随着每

次编辑修改后递增。

更多推荐

writeline