天天看点

2-Windows 窗体应用程序模型

Windows 窗体的应用程序编程模型主要由窗体、控件及其事件组成。MDI 窗体。MDI 窗体可以在其工作区内包含名为 MDI 子窗体的其他窗体。Form 类为键盘处理(Tab 键顺序)和滚动窗体的内容提供内置的支持。

 窗体

在 Windows 窗体中,Form 类是在应用程序中显示的任何窗口的表示形式。可以使用 Form 类的 BorderStyle 属性创建标准窗口、工具窗口、无边框窗口和浮动窗口。还可使用 Form 类创建有模式窗口,如对话框。通过设置 Form 类的 MDIContainer 属性,可以创建一种特殊类型的窗体 MDI 窗体。MDI 窗体可以在其工作区内包含名为 MDI 子窗体的其他窗体。Form 类为键盘处理(Tab 键顺序)和滚动窗体的内容提供内置的支持。

当为应用程序设计用户界面时,通常创建一个从 Form 派生的类。然后可以添加控件、设置属性、创建事件处理程序以及向窗体添加编程逻辑。

控件

添加到窗体中的每个组件(如 Button、TextBox 或 RadioButton)称为控件。Windows 窗体包括通常与 Windows 关联的所有控件以及类似 Windows 窗体 DataGrid 的自定义控件。

通常可以通过设置属性与控件进行交互,以更改其外观和行为。例如,下面的 Form 的派生类向窗体添加一个 Button 控件,并设置该控件的 Size 和 Location。

C# source:

public class HelloWorldForm : System.Windows.Forms.Form {

    private Button button1 = new Button() ;

    private TextBox textBox1 = new TextBox();

    [STAThread]

    public static int Main(string[] args) {

        Application.Run(new HelloWorldForm());

        return 0;

    }

    public HelloWorldForm() {

        this.Text = "Hello Windows Forms World";

        this.AutoScaleBaseSize = new Size(5, 13);

        this.ClientSize = new Size(392, 117);

        this.MinimumSize = new Size(392, (117 + SystemInformation.CaptionHeight));

        this.AcceptButton=button1;

        button1.Location = new Point(256, 64);

        button1.Size = new Size(120, 40);

        button1.TabIndex = 2;

        button1.Text = "Click Me!";

        button1.Click += new System.EventHandler(button1_Click);

        textBox1.Text = "Hello Windows Forms World";

        textBox1.TabIndex = 1;

        textBox1.Size = new Size(360, 20);

        textBox1.Location = new Point(16, 24);

        this.Controls.Add(button1);

        this.Controls.Add(textBox1);

    }

}

VB source:

Public Class HelloWorldForm

    Inherits Form

    Private components As Container

    Private WithEvents button1 as Button

    Private textBox1 As New TextBox

    <STAThread()> Shared Sub Main()

        System.Windows.Forms.Application.Run(New HelloWorldForm())

    End Sub

    Public Sub New()

        MyBase.New

        Me.Text = "Hello Windows Forms World"

        Me.AutoScaleBaseSize = new Size(5, 13)

        Me.ClientSize = new Size(392, 117)

        Me.MinimumSize = new Size(392, (117 + SystemInformation.CaptionHeight))

        button1 = new Button()

        button1.Location = new Point(56, 64)

        button1.Size = new Size(90, 40)

        button1.TabIndex = 2

        button1.Text = "Click Me!"

        textBox1.Text = "Hello Windows Forms World"

        textBox1.TabIndex = 1

        textBox1.Size = new Size(360, 20)

        textBox1.Location = new Point(16, 24)

        Me.AcceptButton=button1

        Me.Controls.Add(button1)

        Me.Controls.Add(textBox1)

    End Sub

End Class

控件状态为无模式

窗体对于何时可设置控件的属性提供有限的限制。控件没有阻止更新其状态的模式。创建控件的新实例后,可以立即更改其状态。例如,下面的代码提供两个示例,演示创建 Button 控件的有效方法。

C# source:

Button button1 = new Button();

button1.Location = new Point(256, 64);

button1.Size = new Size(120, 40);

button1.TabIndex = 1;

button1.Text = "Click Me!";

this.Controls.Add(button1);

VB source:

Dim button1 As New Button

button1.Location = New Point(256, 64)

button1.Size = New Size(120, 40)

button1.TabIndex = 1

button1.Text = "Click Me!"

Me.Controls.Add(button1)

事件

Windows 窗体编程模型基于事件。当控件更改状态,如当用户单击按钮时,它引发一个事件。为了处理事件,应用程序为该事件注册一个事件处理方法。 在 Visual Basic 中,有两种途径可以注册事件处理方法:

如果使用 WithEvents 关键字声明控件变量,可以在方法的声明中使用 Handles 关键字,将该方法注册为事件处理方法。 可使用 AddHandler 在运行时注册事件处理方法。

下面的代码阐释注册事件处理方法的两种途径。

C# source:

public delegate void EventHandler(object sender, EventArgs e);

VB source:

Public Delegate Sub EventHandler(sender As object, e As EventArgs)

 Click 事件的任何事件处理方法都必须具有以下签名。

C# source:

<access> void <name>(object sender, EventArgs evArgs)

VB source:

<access> Sub <name>(sender As object, e As EventArgs)

 对于强类型语言,如果事件处理方法的签名与委托签名不匹配,将发生编译时错误。

很多事件使用一般的 EventHandler 和 EventArgs 类。但是,一些事件要求针对所引发事件的类型的附加信息。例如,鼠标移动事件包括有关鼠标指针或鼠标按钮位置的信息。这些事件定义其自己的类,这些类必须从 EventHandler 和 EventArgs 类继承。例如,MouseDown 事件使用 MouseEventHandler 和 MouseEventArgs 类。

事件命名约定

可以在特定种类的状态更改之前和之后引发事件。在状态更改前引发的事件通常带有后缀“ing”。在状态更改后引发的事件通常带有后缀“ed”。例如,SessionEnding 事件是状态更改前引发的,SessionEnded 事件是状态更改后引发的。如果某状态更改仅导致一个事件被引发,则该事件通常没有后缀。例如,Click 事件。

可取消的事件

根据应用程序中的情况,可能需要取消某个事件。某些事件可以取消。这些事件使用 CancelEventHandler 和 CancelEventArgs 类。CancelEventArgs 类包含名为 Cancel 的属性。如果此属性设置为 true,那么当该事件处理方法返回时,将取消该事件。通常,只有在状态更改前引发的事件才是可以取消的。取消事件将取消状态更改。

用一个事件处理方法处理多个事件

如果要用一个事件处理程序处理多个事件,可通过将同一方法注册到多个事件来实现。每个事件都必须具有相同的签名。当对多个事件使用一个事件处理方法时,可以从 sender 参数确定哪个控件引发了事件。下面的示例阐释处理来自两个按钮控件的事件的单个事件处理方法。

C# source:

....

Button button1 = new Button() ;

Button button2 = new Button() ;

....

button1.Click += new System.EventHandler(button_Click);

button2.Click += new System.EventHandler(button_Click);

....

//The event handling method

private void button_Click(object sender, EventArgs evArgs) {

    if (sender==button1) {

        MessageBox.Show("Button1 Pushed!");

    } else if (sender==button2) {

        MessageBox.Show("Button2 Pushed!");

    }

}

VB source:

....

Dim button1 As New Button

Dim button2 As New Button

....

AddHandler button1.Click, AddressOf button_Click

AddHandler button2.Click, AddressOf button_Click

....

'The event handling method

Private Sub button_Click(sender As Object, evArgs As EventArgs)

    If (sender = button1) Then

        MessageBox.Show("Button1 Pushed!")

    Else If (sender = button2) Then

        MessageBox.Show("Button2 Pushed!")

    End If

End Sub

下面的示例演示前面提到的概念。它显示如何:

创建和显示一个作为应用程序主入口点的窗体

向窗体添加控件

设置控件上的属性

将事件处理方法注册到控件

从控件获取属性值

在消息框中显示文本

向关闭窗体时执行的 Dispose 方法添加代码

VB source:

Imports System Imports System.ComponentModel

Imports System.Drawing

Imports System.Windows.Forms

Namespace Microsoft.Samples.WinForms.VB.HelloWorldForm

    Public Class HelloWorldForm

        Inherits Form

        Private components As Container

        '使用 WithEvents 声明按钮,以便能够注册声明性事件处理程序

        Private WithEvents button1 as Button

        Private textBox1 As New TextBox

        '应用程序启动时显示此窗体

        <STAThread()> Shared Sub Main()

            System.Windows.Forms.Application.Run(New HelloWorldForm())

        End Sub

        Public Sub New()

            MyBase.New

            '设置窗体

            Me.Text = "Hello Windows Forms World"

            Me.AutoScaleBaseSize = new Size(5, 13)

            Me.ClientSize = new Size(392, 117)

            '将最小窗体大小设置为工作区的大小,高度与标题栏相同

            Me.MinimumSize = new Size(392, (117 + SystemInformation.CaptionHeight))

            '创建 button1

            button1 = new Button()

            button1.Location = new Point(56, 64)

            button1.Size = new Size(90, 40)

            button1.TabIndex = 2

            button1.Text = "请单击我!"

            '创建文本框

            textBox1.Text = "Hello Windows Forms World"

            textBox1.TabIndex = 1

            textBox1.Size = new Size(360, 20)

            textBox1.Location = new Point(16, 24)

            '在窗体上设置默认按钮

            Me.AcceptButton=button1

            '向窗体添加控件

            Me.Controls.Add(button1)

            Me.Controls.Add(textBox1)

        End Sub

        '当窗体关闭时调用

        '注意,MessageBox 调用只是说明调用了 Dispose。

        '应使 Dispose 方法代码尽可能地简单可靠

        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

            Try

                MessageBox.Show("已处置!")

            Catch ex As Exception

            End Try

            MyBase.Dispose(disposing)

        End Sub

        'button2 的事件处理方法 - 使用 Handles 注册

        Private Sub button1_Click(sender As Object, evArgs As EventArgs) Handles button1.Click

            '禁用 button1 - 我们只想添加一个按钮

            button1.Enabled=False

            '添加新按钮,并使用 AddHandler 添加事件处理程序

            Dim newButton As new Button

            newButton = new Button()

            newButton.Location = new Point(256, 64)

            newButton.Size = new Size(90, 40)

            newButton.TabIndex = 4

            newButton.Text = "还请单击我!"

            Me.Controls.Add(newButton)

            AddHandler newButton.Click, AddressOf Me.clickNewbutton

        End Sub

        '新按钮的事件处理方法 - 使用 AddHandler 注册

        Private Sub clickNewbutton(sender As Object, evArgs As EventArgs)

            MessageBox.Show("来自新按钮的问候")

        End Sub

    End Class

End Namespace

C# source:

namespace Microsoft.Samples.WinForms.Cs.HelloWorldForm {

    using System;

    using System.Windows.Forms;

    using System.Drawing;

    // 不要向 Windows 窗体设计器中加载此窗体。

    // 此“快速入门”是包含控件的简单手写

    // 窗体的一个示例。

    public class HelloWorldForm : System.Windows.Forms.Form {

        private Button button1 = new Button() ;

        private TextBox textBox1 = new TextBox();

        //应用程序启动时显示此窗体

        [STAThread]

        public static int Main(string[] args) {

            Application.Run(new HelloWorldForm());

            return 0;

        }

        public HelloWorldForm() {

            //设置窗体

            this.Text = "Hello Windows Forms World";

            this.AutoScaleBaseSize = new Size(5, 13);

            this.ClientSize = new Size(392, 117);

            //将最小窗体大小设置为工作区的大小,高度与标题栏相同

            this.MinimumSize = new Size(392, (117 + SystemInformation.CaptionHeight));

            //在窗体上设置默认按钮

            this.AcceptButton=button1;

            //创建按钮

            button1.Location = new Point(256, 64);

            button1.Size = new Size(120, 40);

            button1.TabIndex = 2;

            button1.Text = "请单击我!";

            //注册事件处理程序

            button1.Click += new System.EventHandler(button1_Click);

            //创建文本框

            textBox1.Text = "Hello Windows Forms World";

            textBox1.TabIndex = 1;

            textBox1.Size = new Size(360, 20);

            textBox1.Location = new Point(16, 24);

            //向窗体添加控件

            this.Controls.Add(button1);

            this.Controls.Add(textBox1);

        }

        //当窗体关闭时调用

        //注意,MessageBox 调用只是

        //说明调用了 Dispose。

        //应使 Dispose 方法代码尽可能地

        //简单可靠

        protected override void Dispose(bool disposing)

        {

            try {

                MessageBox.Show("已处置!");

            } catch(Exception) {}

            base.Dispose(disposing);

        }

        //事件处理方法

        private void button1_Click(object sender, EventArgs evArgs) {

            MessageBox.Show("文本是:'" + textBox1.Text + "'");

        }

    }

}

继续阅读