65.9K
CodeProject 正在变化。 阅读更多。
Home

构建基本的 Windows 应用程序

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (7投票s)

2009年10月22日

CPOL

8分钟阅读

viewsIcon

38301

downloadIcon

819

一篇解释 Windows Forms 某些方面的文章

构建基本的 Windows 应用程序

简介:一点历史

关于 Windows Forms 的文档很多。本文档旨在面向 Windows Forms 的初学者或中级爱好者。大多数商业应用程序都不是控制台应用程序。相反,它们将使用包含控件的用户界面,用户可以通过这些控件执行操作。早期的 Windows 应用程序需要使用原始的 Windows API,例如 RegisterClass、CreateWindow、ShowWindow、GetMessage、TranslateMessage 和 Dispatch Message。您的应用程序需要一个 WinMain 入口点。在此函数中,您将应用程序向 Windows 注册,创建并显示一个窗口,并处理来自系统的消息。每个 Windows 应用程序都必须有一个消息循环,该循环收集 Windows 消息并将其分派到您通过 RegisterClass 函数注册的消息处理函数。作为开发人员,您的精力大部分都集中在处理 Windows 消息上,例如 WM_CREATE、WM_SIZE 或 WM_CLOSE,您必须通过 PostMessage 或 SendMessage 创建并将它们泵入系统。这种早期的 Windows 开发方式很繁琐。结果是构建了应用程序框架来抽象所有这些 Windows API。MFC 和 ATL 等框架是为了帮助开发人员解决如何处理某些 Windows 消息的业务问题而创建的。这些框架提供了 Windows 应用程序的“管道”或“模板”。

当今的 Windows 应用程序主要基于 Windows Forms,它为标准的 Windows 应用程序开发提供了一个统一的编程模型。鉴于 .NET Framework 的目标是拥抱 Web,Windows Forms 桌面应用程序可以与 Web 交互,Web 也可以与桌面应用程序交互。如果应用程序包含在浏览器中,则称为 Web Form。如果应用程序在桌面上运行,则称为 Windows Form。Windows Forms 架构相对简单。它以控件和容器的形式存在。System.Windows.Forms 命名空间中的大多数用户界面类都派生自 Control 类。如果一个控件可以包含另一个控件,那么它就是一个容器。本文将重点介绍 Windows Forms 开发,目的是从基础开始,逐步开发一个基本的桌面游戏。虽然演示的应用程序可能看起来通用且重复,但它们可以作为扩展的模型。

手动开发 Windows Forms 应用程序

事件是 Windows Forms 应用程序的核心,也是开发 Windows Forms 应用程序的核心。当我们手动开发 Windows Forms 应用程序时,我们使用 Forms 的隐喻来进行用户界面的快速应用程序开发。为此,您需要从 System.Windows.Forms.Form 派生。然后,您可以创建小部件,如 System.Windows.Forms.Label,之后您可以设置小部件的文本、位置和大小。最后,您需要设置事件处理程序以响应任何用户交互,并将这些小部件添加到窗体的控件集合中。

using System;
using System.Windows.Forms;
using System.Drawing;

  public class myForm : Form
  {
     private System.Windows.Forms.Label output;
     private System.Windows.Forms.Button cancel;
   
// create contructor for the Form, which must be the same name as the class    //itself
   
 public myForm()
     {
      // create the objects
       output = new  System.Windows.Forms.Label();
       cancel = new System.Windows.Forms.Button();
    
      // set the form's title
       Text = "Hello World from C# Forms";
      // setup output label; we have to tell it where to put the label
       output.Location = new System.Drawing.Point(20, 30);
       output.Text = "Hello World from C# Forms";
       output.Size = new System.Drawing.Size(200, 25);
       cancel.Location = new System.Drawing.Point(150, 200);
       cancel.Text = "&Cancel";
       cancel.Size = new System.Drawing.Size(110, 30);

      // set up the event handler
        cancel.Click += new System.EventHandler(this.onCancelclick);

      // add the controls
       Controls.Add(cancel);
       Controls.Add(output);
    } 
      // end constructor


     protected void onCancelclick(object sender, System.EventArgs e)
     {
       Application.Exit();
     }

     // now we need an entry point for the application
      public static void Main()
     {
        Application.Run(new myForm());
     }
   }

        

/* * * 输出: * * */

a.JPG

从界面来看,我们完全可以在其中添加一些功能。事实上,我们将设计一个名为“Lucky Seven”的游戏。Lucky Seven 有三个标签,其中包含整数。当单击“spin”(旋转)按钮时,这些整数由 C# 中的随机数生成器函数生成。每当出现数字七时,一个图像就会弹出到窗体上。我们开始构建一个 Visual C# Windows 应用程序,并将其命名为 MySeven。我们将两个按钮拖放到左上角,并分别将其文本属性设置为 Spin 和 Close。然后我们将四个 Label 控件拖放到窗体表面,其中三个将构成旋转按钮右侧的一行。最后,我们将一个 Picture 控件拖放到第四个标签的右侧,该标签位于 Close 按钮下方。现在,在编写任何代码之前,必须设置这三个标签的属性。单击 AutoSize 属性设置为 false,以便您可以手动调整标签大小。将 TextAlign 属性设置为 Middle Center。单击 BorderStyle 属性并选择 FixedSingle。将 Font更改为 New Times Roman,将 Font Style 更改为 bold,并将 Point Size 设置为 24,然后单击 OK。现在,为这三个标签设置数值 0 作为 Text 属性。

现在设置窗体上的第四个标签对象(Label4)。将 Text 属性更改为 LuckySeven。单击 Font 属性,然后单击省略号按钮。使用 Font 对话框将字体设置为 Arial,将 Font Style 设置为 bold,并将 Point Size 设置为 18,然后单击 OK。请注意,Label 对象的大小(位于 Close 按钮下方的第四个标签)已更新,并且标签会自动调整大小以容纳更大的字体大小,因为对象的 AutoSize 属性设置为 True。现在,在 Properties 窗口中单击 ForeColor 属性,然后单击第二列中的箭头。选择 Custom 选项卡并选择 purple。现在出现在标签框中的文本将变为紫色。现在我们可以设置最后一个对象——Picture Box 的属性了。

在窗体上单击 picture box。在 Properties 窗口中单击 SizeMode 属性,然后在第二列中单击 StretchImage。此属性将强制图像的大小以比例缩放来适应框。单击 Image 属性,然后单击第二列中的省略号按钮。此时将出现 Select Resource 对话框。在 Open 对话框中,导航到 c:\users\name\Pictures\SamplePictures 文件夹并选择一个图像。调整 picture box 对象的大小以修复您可能看到的任何图像失真问题。您可能希望将其大小调整为 148 像素宽 x 138 像素高。现在,我们将 picture box 对象的可视属性设置为 False,以便在程序启动时图像是不可见的。

      b.JPG

以下是 Form1.cs 的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security;
using System.Text;
using System.Windows.Forms;


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random r = new Random();
            pictureBox1.Visible = false;

            int rand1 = r.Next(1, 9);
            int rand2 = r.Next(1, 9);
            int rand3 = r.Next(1, 9);

            label1.Text = rand1.ToString();
            label2.Text = rand2.ToString();
            label3.Text = rand3.ToString();



            if (rand1 == 7 || rand2 == 7 || rand3 == 7)  // or is ||
            {
                pictureBox1.Visible = true;
            }

        }
    }

这是主程序的代码

using System;
using System.Collections.Generic;
using System.Security;
using System.Windows.Forms;

  static class Program
    {
        
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

最后,这是 IDE 生成的 Designer 代码

    partial class Form1
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(24, 27);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Spin";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(24, 80);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "End";
            this.button2.UseVisualStyleBackColor = true;
            // 
            // label1
            // 
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(169, 27);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(100, 45);
            this.label1.TabIndex = 2;
            this.label1.Text = "0";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label2
            // 
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label2.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(275, 27);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(90, 45);
            this.label2.TabIndex = 3;
            this.label2.Text = "0";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label3
            // 
            this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label3.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(366, 27);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(100, 45);
            this.label3.TabIndex = 4;
            this.label3.Text = "0";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
            this.label4.Location = new System.Drawing.Point(24, 175);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(130, 22);
            this.label4.TabIndex = 5;
            this.label4.Text = "Lucky Seven";
            // 
            // pictureBox1
            // 
            this.pictureBox1.ErrorImage = null;
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(275, 108);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(191, 190);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 6;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.Visible = false;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(574, 325);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.PictureBox pictureBox1;
    }


当随机数生成器在单击 Spin 按钮时生成数字七时,游戏界面如下(显然,Close 按钮会关闭应用程序)

       Capture1.JPG

Timer 控件

尽管计时器对象在运行时不可见,但每个计时器都关联了一个事件过程,该过程在每次设置了计时器的预设间隔后运行。您可以使用 Interval 属性来设置计时器的间隔,并通过将计时器的 Enabled 属性设置为 true 来激活计时器。一旦计时器被启用,它就会不断运行——按照规定的间隔执行其事件过程——直到用户停止计时器或计时器被禁用。创建一个小型 Visual C# Windows Forms 应用程序。拖放一个 timer 控件,将其 Interval 设置为 1000(毫秒),并将其 Enabled 属性设置为 true。将窗体的 Text 属性设置为“Clock”。将一个 label 控件拖放到窗体的中心。将 AutoSize 属性设置为 False,将 Font 设置为 Times New Roman,粗体,24 点,将 Text 属性留空,并将 TextAlign 属性设置为 MiddleCenter。现在,双击 timer 控件,然后输入此代码

private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = System.DateTime.Now.ToString();
        }

这是您的基本数字时钟

c.JPG

使用 For 循环创建图像序列

假设我们有四个图标,每个图标都是一个通用的黄色笑脸。每个笑脸都显示不同的表情。我们希望显示这些图像,也许在达到某个条件时,该表情能够体现当前的状态。我们可以使用 for 循环在按钮单击事件处理程序中进行迭代,其中 Picture Box 控件会显示这样的图像。因此,最后一点,让我们开始一个 Visual C# Forms 项目并将其命名为 icons。我们将一个 picture box 控件拖放到窗体的中心,并在其下方拖放一个 button 控件。我们将 PictureBox 的 BorderStyle 属性设置为 Fixed3D,并将 SizeMode 设置为 StretchImage。然后,我们将 button 控件的 text 属性设置为“Display four faces”。现在,我们双击“Display four faces”按钮来编写事件处理程序。

文件:Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace icon
{
  public partial class Form1 : Form
    {
   public Form1()
   {
   InitializeComponent();
  }

 private void button1_Click(object sender, EventArgs e)
 {

  for (int i = 1; i <= 4; i++)
   {
pictureBox1.Image = System.Drawing.Image.FromFile(@"c:\users\dave\desktop\face0" + i + ".ico");

  MessageBox.Show("click here for next face.");

         }
        }
      }
    }
    

请注意,我将四个图标存储在我的桌面上,因此路径的设置方式是作为参数传递的。另外请注意,由于我们处理的是图标加载,所以我们不将这 4 个图标视为数组,因此我们不会将变量初始化为零。以下是代码,但它被组装成在控制台运行:您只需在提示符处键入:c:\..|.NET> type con > face.cs

从那里您将看到一个没有提示符的光标。将代码复制并粘贴到提示符处。确保将这些笑脸复制并粘贴到您的桌面,或者您喜欢设置路径的任何位置。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.Button button1;
     public Form1()
   {InitializeComponent();}
   private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pictureBox1.Location = new System.Drawing.Point(35, 24);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(214, 164);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(81, 216);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(113, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Display 4 Faces";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.ClientSize = new System.Drawing.Size(303, 264);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
      }
         [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
  private void button1_Click(object sender, EventArgs e)
   {

  for (int i = 1; i <= 4; i++)
   {

   pictureBox1.Image = System.Drawing.Image.FromFile(@"c:\users\dave\desktop\face0" + i + ".ico");

  MessageBox.Show("click here for next face.");

         }
      }
   }

        x.JPG

        z.JPG

单击消息框中的 OK 会显示四个笑脸中的一个,它们在按钮单击序列中迭代。

参考文献:.NET Framework Essentials,作者:Thuan Thai & Hoang Q. Lam

构建基本 Windows 应用程序 - CodeProject - 代码之家
© . All rights reserved.