C#编程之C# 基础知识
小标 2018-09-17 来源 : 阅读 2004 评论 0

摘要:本文主要向大家介绍了C#编程之C# 基础知识,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之C# 基础知识,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。


类型和变量
类型
C# 支持两种类型:"值类型"和"引用类型"。值类型包括简单类型(如 char、int 和 float等)、枚举类型和结构类型。引用类型包括类 (Class)类型、接口类型、委托类型和数组类型。 
变量的类型声明
每个变量必须预先声明其类型。如
int a; 
    int b = 100; 
    float j = 4.5; 
    string s1; 
用object可以表示所有的类型。 
预定义类型

变量转换
简单转换:
float f = 100.1234f; 
可以用括号转换:
short s = (short)f
也可以利用Convert方法来转换:
string s1; 
    s1=Convert.ToString(a); 
    MessageBox.Show(s1); 

枚举型
一般为字符串,可以定义带数字的枚举型,示例为:
        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的程序调用。
 
数组
定义
数组是一种排列有序的数据结构,包含于数组中的变量被称为数组的元素,它们都有相同的类型。
数组声明
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 类型可隐式转换为 ushort、int、uint、long、ulong、float、double 或 decimal 类型。但是,不存在从其他类型到 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, my    

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved