Create a Windows application using Microsoft.NET Frameworks

zhaozj2021-02-08  216

Create a Windows-based application with Microsoft.NET Frameworks Shawn Burke

Microsoft Corporation

September 2000

Summary: This article introduces this new form package this package, with this package, developers fully utilize the UI functionality provided by Microsoft Windows operating systems.

table of Contents

Introduction Description Win Forms better easy to learn easily layout GDI access to the underlying system conclusion

Introduction

At present, Web has become a topic of street talks, which seems to be weakened by Microsoft® Visual Studio® development system to create Microsoft Windows® traditional applications. In fact, Microsoft's investment in Windows-based applications is increasing.

The WIN form is a new form package, with this package, developers fully utilize the rich user interface features provided by the Microsoft Windows® operating system, create a Windows-based application. Win Forms is an integral part of the new Microsoft®.NET platform, which provides many new technologies, including universal application frameworks, manageable execution environments, integrated security, and object-oriented design principles. Moreover, Win Forms fully supports fast and easy access to Web Services and establish a rich data perceived application based on ADO data model. Thanks to the new shared development environment in Visual Studio, developers can create WINFORMS applications using any language including Microsoft Visual Basic® and C #.

Introduction WIN FORMS

Just as I said, Win Forms is a namespace dedicated to the WINDOWS client UI programming. Net framework. It shares the same design principle as the ASP UI package (ie Web Forms), but its classes and implementations are all different. There is no magic deformation between the Microsoft Win32® API and WEB components. Just like all .NET Frameworks, consistency has become a priority problem. Its purpose is to quickly adapt to WIN FORMS developers to write code in Web Forms and vice versa. For example, all namespaces have a Button class, each with text, default onclick event, and Forecolor, Backcolor, and Font properties.

All controls for WIN FORMS are based on the System.winForms.Control class. Control has built-in all basic hwnd features, and it can handle most of the general WM_XXXX messages we are familiar with and love. RichControl is derived from Control, which adds layout logic and drawing code. Most of the controls in the System.winForms namespace are actually derived from RichControl. ScrollableControl supports scrolling from the window customer area. In general, support for scrolling functions is implemented by ContainerControl, the latter is derived from ScrollableControl and adds support for managed sub-controls, focus issues, and hurdles. The Form is derived from ContainerControl, which is a top-level control of Win Form, which has the properties of the control title bar, the system menu, the non-rectangular window, and the default control. UserControl is also derived from ContainterControl and is the basic class of the controls that developers can create. UserControl is typically used to host other sub-controls, but for external clients, it is as a single unit. UserControl and Form have a visual designer in Microsoft® Visual Studio.net, you will find items for adding and designing the classes they are. Figure 1. Win Forms Control Hierarchy

Since we have learned the basic aspects of Win Forms, let us unveil its veil and see some of its considerable features under its surface.

Better easy to learn ease of use

The main purpose of Win Forms is to increase the work efficiency of developers positioned to the Win32 platform as much as possible. Whether it is a graphic device interface (GDI) or window state management, it is often difficult for Win32 programming. For example, some window patterns like WS_Border or WS_CAPTION can only be specified or modified when creating a window. Other window styles such as WS_Visible or WS_CHILD can be modified to the created window. WIN FORMS is trying to eliminate these subtle differences and ensure that the operation process is always consistent. You can set the properties of the Win Forms control at any time, which can always generate expected results. If the change process needs to create a new HWnd, the Win Forms framework can be automatically, transparently regenerated, and all settings appropriately apply.

The notification or event is much easier in Win Forms. Win Forms event is based on a general language runtime function called Delegates. Delegates is essentially a safe, reliable function pointer to type. For any event of any control, you can add a proxy handler; you will never force you to create a derived class to implement an interface by replacing the event, creating an event mapping, or only for all events for the class. It is also possible to replace the events to process events, but this approach is generally used for control creators or more advanced applications. Collect a button's Click event is quite simple:

Public class buttonclickform: system.winforms.form {

Private system.winforms.button button1;

Public buttonclickform () {

// Create button

Button1 = new system.winforms.button ();

// Add a handler

Button1.addonClick (New System.EventHandler (Button1_Click);

// Add the button to the form

This.Controls.Add (Button1);

}

Private void button1_click (object sender, evenetargs e) {messagebox.show ("Button1 Clicked!");

}

}

Here, we created a button and added a handler method called Button1_Click, which will call this method by shorting a few lines of code. Note that even if the handler method is marked as a dedicated, creating this hook can still use this method. After the button is clicked, the button will be able to activate the event of this method.

The process of launching the WIN FORMS project has also been simplified. The process of creating a Win Forms project using Visual Studio.NET will only create item files to be compiled: form1.cs. There is no header file, there is no interface definition file, no boot program file, no resource file, no library file. All information required for the project is included in the code of the form. This has a benefit: The project extends from a simple single-window application to complex, multi-warte applications with multiple code files. The link process does not require an intermediate object file, only the code and all the managed, managed DLLs. As long as you are accustomed to this method, you can clearly feel the difference between the creation .NET Framework application and the creation of C / C applications. Because the information is only included in the code file, the process of creating a version outside the Visual Studio.NET environment is also very easy. Whether it is Visual Basic code, C # code, or any other language written in the code for .NET Framework.

Because Win Forms is based on the general language runtime, developers can optionally build a Win32 application in many languages ​​that are currently running in general language. Developers can now write Win Forms applications (or Web Forms applications or DATA applications): from C # to COBOL to Eiffel to Perl, etc., there are many kinds in the middle (the last count is 17) . It is convenient to use a wide range of applications to complement, providing developers with a deep basis, enabling them to quickly and effectively build a practical application using Win Forms.

layout

If you have tried to create a form that can normally resize, you will know how difficult this process is. Microsoft Foundation Classes (MFC) or early Visual Basic version does not provide built-in support for this feature. However, now only a few lines of code (usually you don't even need to write these code, because these features can be implemented through the Property Browser when designing!), You can create a dialog that can be normally resized.

Basic layouts consist of two complications: Anchoring and Docking. RichControl has an Anchor property that is an enumeration type that can be combined with "or" to explain these values ​​to the explanation of constant distances with your parent control. For example, if you place a button on the form and set the Anchor property to Anchorstyles.Bottomright, the button will be the same distance from the bottom of the form and the right side at the bottom of the window. In addition, if the Anchor is set to Anchorstyles.all, the respective edges of the button remain the same distance from the corresponding edge of the form, and these constraints are still met when the adjustment button is in size.

Docking is actually a special case of Anchoring. RichControl's Dock property description control is to secure itself to which side of its parent control. Docking can be Top, Left, Right, Bottom or Fill. In each case, the control will move to the specified edge as much as possible, and adjust its size to fill it over. This situation will remain in this situation if the size of the parent control is adjusted. Move a control to the bottom of the parent control and set the AnchorStyle.BottomLightright to simulate Docking Bottom. In the example here, the list box is a docked left, buttons are kept at the top of the form, the left and right edges remain constant, thereby maintaining relative positions and sizes. The following example dialog (Figure 2) is completely created using the Win Forms designer in Visual Studio.NET, only spent two minutes, no code. Figure 2. Dialog box created using the Win Forms Designer

// resizablesample.cs

Namespace ResizablesampleNamespace {

Using system;

Using system.drawing;

Using system.componentmodel;

Using system.winforms;

///

A summary description of /// Resizablesample.

///

Public class resizablesample: system.winforms.form {

///

/ / / Is required for the Win Forms designer

///

Private system.componentmodel.Container Components;

Private system.winforms.button button3;

Private system.winforms.button button2;

Private system.winforms.button button1;

Private system.winforms.listbox listbox1;

Public Resizablesample () {

/ / Support for WIN FORM Designer Support

InitializationComponent ();

}

///

/// Release all resources being used

///

Public override void dispose () {

Base.dispose ();

Components.dispose ();

}

///

/// The main entry point for the application.

///

Public static void main (String [] args) {

Application.run (New Resizablesample ());

}

///

/// Designer supports the required method - do not use editors

// / Modify the content of this method

///

Private vidinitiRizeComponent ()

{

This.Components = new system.componentmodel.container ();

This.button2 = new system.winforms.button ();

THIS.BUTTON3 = New System.winForms.Button ();

This.button1 = new system.winforms.button (); this.listbox1 = new system.winforms.listbox ();

@ Design this.trayLargeicon = FALSE;

@ Design this.trayHeight = 0;

THIS.TEXT = "resizable dialog";

THISTEMEMODE = system.winforms.imemode.off;

THIS.AUTOSCALEBASESIZE = New System.drawing.size (5, 13);

This.ClientSize = New System.drawing.size (256, 173);

Button2.location = new system.drawing.point (152, 60);

Button2.size = new system.drawing.size (92, 32);

Button2.tabindex = 2;

Button2.anchor = system.winforms.Anchorstyles.toplefTright;

Button2.text = "ca Zancel";

Button3.Location = new system.drawing.point (152, 120);

Button3.size = new system.drawing.size (92, 44);

Button3.tabindex = 3;

Button3.anchor = system.winforms.Anchorstyles.all;

Button3.text = "filler";

Button1.location = new system.drawing.point (152, 8);

Button1.size = new system.drawing.size (92, 32);

Button1.tabindex = 1;

Button1.anchor = system.winforms.Anchorstyles.toplefTright;

Button1.text = "ok";

Listbox1.size = new system.drawing.size (120, 173);

Listbox1.dock = system.winforms.dockstyle.Left;

Listbox1.tabindex = 0;

ListBox1.items.all = new object [] {"item one",

Item TWO,

"Item Three",

Item Four "};

This.Controls.Add (Button3);

This.Controls.Add (Button2);

This.Controls.Add (Button1);

This.Controls.add (listbox1);

}

}

}

GDI

Win Forms fully utilizes GDI this Microsoft's next generation of two-dimensional graphics system. The graphic programming mode in Win Forms is completely object-oriented, a wide variety of brushes, brushes, images, and other graphics objects, like other parts of .NET Framework, follows the simple and easy-to-use guidelines. Developers are currently available to some of the new features such as Alpha mixing, gradient, texture, eliminating serrations, and other image formats other than the extension map. With Windows 2000 hierarchical and transparent window functions, developers can create rich, more graphic Win32 applications. If the onpaint event of the control is triggered, you can be a GDI graphic object by the System.drawing.Graphics object accessed by Painteventargs. All operations that the graphic object can perform are implemented by GDI . As an example, use GDI to create a button to draw a gradient background.

Figure 3. Button created using GDI

The following is the code that implements this button:

Public Class GradientButton: Button {

/ / Keep a member of color settings

Private Color StartColor;

PRIVATE color endcolor;

// We will need it when writing text

Private static stringFormat Format = new stringFormat ();

Public gradientButton (): base () {

// Initialize color

STARTCOLOR = systemcolors.inactivecaption;

EndColor = systemcolors.activecaption;

Format.Alignment = stringalignment.center;

Format.LineAlignment = stringalignment.center;

}

///

/// Termination color of the gradient

//

PUBLIC color endcolor {

Get {

Return this.endcolor;

}

SET {

THIS.Endcolor = Value;

// If necessary, it will lead to re-draw

IF (this.isHandlecreated && this.visible) {

Invalidate ();

}

}

}

///

/// Gradient start color

//

Public color startcolor {

Get {

Return this.startcolor;

}

SET {

THIS.STARTCOLOR = Value;

// If necessary, it will lead to re-draw

IF (this.isHandlecreated && this.visible) {

Invalidate ();

}

}

}

Protected Override void onpaint (Painteventargs PE) {

// Draw a conventional background of the button to form

// Border, and so on.

Base.onpaint (PE);

Graphics g = pe.graphics;

Rectangle ClientRect = this.clientRectangle;

/ / Reduce the rectangle to avoid exiting the time

ClientRect.inflate (-1, -1);

// Create a gradient brush, from

// The upper left corner is run to the lower right corner.

Brush backgroundbrush = new lineargradientbrush (New Point (ClientRect.x, ClientRect.y),

New Point (ClientRect.Width, ClientRect.height),

StartColor,

EndColor);

// Fill the background with a gradient ....

G.FillRectangle (Backgroundbrush, ClientRect);

// Write text in the middle of the client area.

g.drawstring (this.text,

THIS.FONT,

New Solidbrush (this.ForeColor),

ClientRect,

Format);

}

}

Just as you can see, this is not very difficult. Thanks to WIN FORMS and GDI object-oriented design, we can implement our GradientButton without writing any complex code, and in the designer, you can operate Text, Font, StartColor, and EndColor through Property Browser.

Access the underlying system

A disadvantage of many frameworks is that if people prepare the application type and the strict consistency in the example and demo, the effect of these framework is quite good, but sometimes developers have discovered that once they want to use the framework, some creative work, In some cases, it will encounter obstacles or fail. If this is encountered, the Win Forms framework can allow developers to access the system infrastructure from beginning to end. Of course, I hope that Win Forms has such an excellent framework that does not enable the user to encounter this, but may happen almost unlimited. All controls have a Handle property that allows access to the control's window handle (HWnd), and the GDI object also provides a similar handle access process. Moreover, Control actually has a protected virtual method called WndProc, which can replace the method to add a processing method for a small number of Win Forms that cannot be supported.

For example, suppose your application is a resource-intensive, you need to respond to WM_Compacting. If the system detects that the memory is insufficient, WM_Compact is broadcast to all high-level windows, you will know that the Win Forms framework does not provide built-in support for this message, whereby the following processing can be added:

///

/// Win32Form1 summary description.

///

Public class compactableform: system.winforms.form {

Private eventHandler Handler;

Public void addonCompacting (EventHandler H) {

delegate.comBBINE (Handler, H);

}

Protected Override Void OnCompacting (Eventargs E) {

/ / View whether the system can release anything

System.gc.collect ();

// Call either handler.

IF (Handler! = NULL) Handler (this, e);

}

Public Void RemoveonCompacting (EventHandler H) {

Handler = (EventHandler) Delegate.Remove (Handler, H);

}

Protected Override Void WndProc (Ref Message M) {

Case (m.msg) {

Case Win.WM_Compacting: OnCompacting (Eventargs.empty);

Break;

}

Base.WndProc (m);

}

}

Just a digital code, when the system tries to collect unused resources, use the new CompactableForm class or the derived class to get notifications, and respond.

in conclusion

Although in many developers's plan, development of Web is the focus of current work, while the familiar Win32 platform is still facing. With WIN FORMS, Windows Developers, both newers or olders, will find that the use of rich interfaces to create complex applications is a very convenient process, and these interfaces are good for many technologies with Web and data features in .NET Framework. .

Developers will benefit from .NET Framework and Win Forms by using a general language operation such as cross-language inheritance, fragment collection and security.

转载请注明原文地址:https://www.9cbs.com/read-3252.html

New Post(0)