To create a Windows application using Microsoft.NET frameworks

Source: Internet
Author: User
Tags constant resource web services win32 visual studio advantage
window| Programs | Create windows-based applications using Microsoft.NET frameworks
Shawn Burke
Microsoft Corporation
September 2000

Summary:: This article describes the Win form, a new form package that enables developers to take full advantage of the UI features provided by the Microsoft Windows operating system.

Directory

Brief introduction
Introducing Win Forms
Easier to learn and ease of use
Layout
Gdi+
Access to the underlying system
Conclusion

--------------------------------------------------------------------------------


Brief introduction

The Web has become a gossip topic, and it looks as if the microsoft®visual studio® development system has weakened support for the creation of legacy applications based on Microsoft Windows®. In fact, Microsoft's investment in windows-based application development is increasing.

The Win form is a new form package that enables developers to take full advantage of the rich user interface features provided by the Microsoft Windows® operating system to create windows-based applications. Win Forms is an integral part of the new Microsoft®.net platform, providing a wide range of new technologies, including a common application framework, a manageable execution environment, integrated security, and object-oriented design principles. Also, Win Forms fully supports fast and easy access to Web Services and the creation of rich data-aware applications based on ado+ data models. Thanks to the new shared development environment in Visual Studio, developers can create a Win Forms application using any language that supports the. NET platform, including Microsoft visual basic® and C #.


Introducing Win Forms

As you've just said, Win Forms is a namespace for the. NET Framework that is dedicated to Windows client UI programming. It shares the same design principles as the asp+ UI package, Web Forms, but its classes and implementations are completely different. A class that is not magically deformed between Microsoft win32®api and Web components. As with all. NET frameworks, consistency has become a priority issue. The goal is to Win the forms developer to quickly adapt to writing code in Web forms, and vice versa. For example, all namespaces have Button classes, each with text, default OnClick events, and ForeColor, BackColor, and Font properties.

All of the controls for Win Forms are based on the System.WinForms.Control class. Control has all the basic HWND features built into it, and it handles most of the common wm_xxxx messages we already know and love. Richcontrol is derived from control, where layout logic and drawing code are added. Most of the controls in the System.WinForms namespace are actually derived from Richcontrol. ScrollableControl can support scrolling of window client areas. In general, support for scrolling functions is implemented through ContainerControl, which is derived from ScrollableControl and increases support for managing child controls, focus issues, and hurdles. The form, derived from ContainerControl, is the top-level control of Win Form with properties that control the title bar, system menus, non rectangular windows, and default controls. UserControl, also derived from Containtercontrol, is the basic class of controls that developers can create. UserControl is typically used to host other child controls, but it appears as a single unit for external clients. UserControl and Form have visual designers in Microsoft®visual Studio.NET, and you find the items that you use to add and design the classes that are derived from them.



Figure 1. Win Forms Control Hierarchy

Now that we have understood the (most) fundamental aspects of Win Forms, let's uncover its veil and look at some pretty good features beneath its surface.


Easier to learn and ease of use

The main purpose of Win Forms is to maximize the productivity of developers who are positioned on the Win32 platform. Whether it's a graphical device interface (GDI) or window state management, programming for WIN32 is often difficult. For example, some window styles like Ws_border or ws_caption can be specified or modified only when the window is created. Other window styles, such as ws_visible or ws_child, can modify the windows you have created. Win Forms tries to eliminate these nuances and ensures that the process remains consistent. The properties of the Win Forms control can be set at any time, in an unlimited order, and always have the desired effect. If the change process requires creating a new Hwnd,win Forms framework to automatically and transparently regenerate the window and apply all the settings appropriate to it.

It is also much easier to get notifications from controls or events in Win Forms. The Win Forms event is based on a common language runtime feature called delegates. Delegates is essentially a type-safe, reliable function pointer. You can add agent handlers for any of the events of any control, and you will never be forced to create a derived class to create an event map by substituting for handling events, or to implement an interface for all the events of a class to handle only one event. You can also handle events by substituting a derived class, but this approach is generally used for control creators or more advanced applications. The Click event that brings together a button is fairly simple:

public class ButtonClickForm:System.WinForms.Form {
Private System.WinForms.Button button1;
Public Buttonclickform () {
Create a button
button1 = new System.WinForms.Button ();
To add a handler
Button1. Addonclick (New System.EventHandler (button1_click));
Add a button to a form
This. Controls.Add (button1);
}

private void Button1_Click (object sender, EventArgs e) {
MessageBox.Show ("button1 clicked!");
}
}

Here, we create a button and add a handler method called Button1_Click, which, after a few lines of code, is invoked when the button is clicked. Note that even if the handler method is marked private, the code that creates the hook can still use the method, and when the button is clicked, the button will be able to activate the event for the method.

The process of starting the Win Forms project has also been simplified. The process of creating a Win Forms project using Visual Studio.NET creates only one project file to compile: Form1.cs. No header files, no interface definition files, no bootstrapper files, no resource files, no library files. All the information required for the project is contained in the form's code. There is a benefit to this: The project is much more convenient to extend from a simple single form application to a complex multiple-form application with multiple code files. The link process does not require intermediate object files, only code and all of the built, managed DLLs. As long as you get used to this approach, you can obviously feel the difference in the complexity of creating a. NET Framework application and creating a C + + application. Because information is contained only in code files, it is also very easy to create a version outside of the Visual Studio.NET environment, whether it is visual Basic code, C # code, or code written in any other language for the. NET Framework.

Because Win Forms is based on the common language runtime, developers can choose to build Win32 applications in one of the many languages currently running for the common language runtime. Developers can now write Win Forms applications (or Web Forms applications or Data applications) in a variety of languages: from C # to COBOL to Eiffel to Perl, among other things (the last count was 17). Ease of use, combined with a wide range of applications, provides a deep foundation for developers to quickly and efficiently use Win Forms to build practical applications.


Layout

If you've ever tried to create a form that resizes correctly, you know how difficult this process is. Microsoft Foundation Classes (MFC) or earlier versions of Visual Basic did not provide built-in support for this feature. However, there are just a few lines of code (usually you don't even need to write them, because they can be implemented by the property Browser at design time!). , you can create a dialog box that resizes correctly.

The basic layout consists of two articles: anchoring and docking. Richcontrol has an Anchor property, which is an enumeration type that can be combined with a "or" operation to show that the control will remain at a constant distance from the side of its parent control. For example, if you place a button on a form and set the Anchor property to Anchorstyles.bottomright, the button will remain at the same distance from the bottom and right of the form when the button is resized. In addition, if you set Anchor to Anchorstyles.all, each edge of the button remains at the same distance from the corresponding side of the form, and these constraints are still met at large hours of the adjustment button.

Docking is actually a special case of anchoring. The Dock property of the Richcontrol describes which side of the control you want to pin itself to the parent control. Docking can be top, left, right, Bottom, or Fill. In each case, the control moves as close to the specified edge as possible and adjusts its size to fill that side. If the size of the parent control is adjusted, this condition will remain. You can simulate docking Bottom by moving a control to the bottom of the parent control and setting the Anchor to Anchorstyle.bottomleftright. In the example here, the list box is docked left, and the button remains at a constant distance from the top, left-hand, and right of the form, which keeps the relative position and size. The following example dialog box (Figure 2) is created entirely with the Win Forms designer in Visual Studio.NET and takes only two minutes to write without a single line of code.



Figure 2. Resizable dialog box created using the Win Forms Designer

ResizableSample.cs
Namespace Resizablesamplenamespace {

Using System;
Using System.Drawing;
Using System.ComponentModel;
Using System.WinForms;

<summary>
Summary description of the resizablesample.
</summary>
public class ResizableSample:System.WinForms.Form {
<summary>
Required for the Win Forms designer
</summary>
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 () {
Supports the Win Form designer for the required
InitializeComponent ();

}

<summary>
Free all resources that are in use
</summary>
public override void Dispose () {
Base. Dispose ();
Components. Dispose ();
}


<summary>
The main entry point for the application.
</summary>
public static void Main (string[] args) {
Application.Run (New Resizablesample ());
}


<summary>
Designer supports the required method-do not use the editor
Modify the content of this method
</summary>
private void InitializeComponent ()
{
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";
This. IMEMode = 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 = "Cancel";
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 leverages GDI +, the Microsoft next-generation two-dimensional graphics system. The graphics programming pattern in Win Forms is entirely object-oriented, with a wide variety of brushes, brushes, images, and other graphic objects, just like the rest of the. NET Framework, followed by simple and easy-to-use guidelines. Developers can now use a fairly good number of new drawing features, such as alpha blending, gradients, textures, anti-aliasing, and other image formats other than bitmaps. Combined with the Windows 2000 operating system's layered and transparent window features, developers can effortlessly create rich, more graphical Win32 applications.

If the control's OnPaint event is triggered, the System.Drawing.Graphics object that can be accessed by PaintEventArgs becomes a GDI + drawing object. All the operations that a drawing object can perform are implemented through GDI +. As an example, use GDI + to create a button that draws a gradient background.



Figure 3. Buttons created by using GDI +

Here's the code to implement this button:

public class Gradientbutton:button {
Members that retain color settings
Private Color StartColor;
Private Color EndColor;

We will need it when writing
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;
}

<summary>
Gradient Color of termination
</summary>
Public Color EndColor {
get {
return this.endcolor;
}
set {
This.endcolor = value;
If necessary, causes a redraw
if (this. Ishandlecreated && this. Visible) {
Invalidate ();
}
}
}


<summary>
The starting color of the gradient
</summary>
Public Color StartColor {
get {
return this.startcolor;
}
set {
This.startcolor = value;
If necessary, causes a redraw
if (this. Ishandlecreated && this. Visible) {
Invalidate ();
}
}
}

protected override void OnPaint (PaintEventArgs pe) {
Draws a general background of a button to form
Borders, and so on.
Base. OnPaint (PE);
Graphics g = pe. Graphics;
Rectangle Clientrect = this. ClientRectangle;
Narrow the rectangle to prevent out of bounds when drawing
Clientrect.inflate ( -1,-1);
Create a gradient brush from
The upper-left corner runs 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 gradients ....
G.fillrectangle (Backgroundbrush, clientrect);
Writes text in the middle of the client area.
g.DrawString (this. Text,
This. Font,
New SolidBrush (this. ForeColor),
Clientrect,
format);
}
}

As you can see, it's not very difficult. Thanks to the Win Forms and GDI + object-oriented design, you can implement our Gradientbutton without writing any complex code, and in the designer, you could manipulate Text, Font, StartColor, and En by using the property Browser Dcolor.


Access to the underlying system

One drawback of many frameworks is that these frameworks work pretty well if they are written in exactly the same type of application as the example and presentation, but sometimes developers find that when they want to do something creative with the framework, there are situations where they encounter obstacles or fail. If this is the case, the Win Forms Framework enables developers to access the system infrastructure from start to finish. Of course, the hope of Win Forms such a well-designed framework does not use the user encounter this situation, but what can happen is almost unlimited. All controls have Handle properties that allow access to the control's window handle (HWND), and a similar handle access procedure is provided by the GDI object. Also, control actually has a protected virtual method named WndProc, which can replace the method and add the processing for messages that are not yet supported by a few Win Forms.

For example, suppose your application is resource-intensive and needs to respond to wm_compacting. If the system detects that there is not enough memory to broadcast wm_compacting to all the top-level windows, you will know that the Win Forms framework does not provide built-in support for this message, and you can add the following processing process:

<summary>
Summary description of the Win32form1.
</summary>
public class CompactableForm:System.WinForms.Form {
Private EventHandler handler;
public void addoncompacting (EventHandler h) {
Handler = (EventHandler) delegate.combine (Handler, h);
}


protected override void Oncompacting (EventArgs e) {
To see if the system can release anything at runtime
System.GC.Collect ();
Invoke any 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);
}

}

With just a few lines of code, when the system tries to collect unused resources, the new Compactableform class or the derived class can be notified and responded to.


Conclusion

While the development of the WEB is the focus of current work in many developers ' plans, positioning on the familiar Win32 platform is still a situation that has to be faced. With Win Forms,windows developers, both novice and veteran, find it a convenient process to create complex applications with rich interfaces that work well with many of the technologies that have WEB and data capabilities in the. NET Framework.

Developers benefit from the. NET Framework and Win Forms by leveraging the excellent features of the common language runtime, such as Cross-language inheritance, fragmentation collection, and security, to improve productivity.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.