How to use C # To create irregular forms

Source: Internet
Author: User

This article from the Xiangyu network http://www.biye5u.com/article/Csharp/winform/2010/2593.html

In the past, most API functions were used to create irregular forms. In C #, you can create beautiful irregular forms without using API functions. The following describes the related methods.

1. First prepare a BMP image.

The image format is random, but it is best to set the image background to some colors provided in C #, such as white (# ffffff \ white) and Black (#000000 \ black), yellow (# FFFF00 \ yellow), blue (# 0000ff \ blue), red (# ff0000 \ red), and green (#00ff00 \ green. This article uses an image in the following format, and its background is white.

2. Create windowsProgram

Open Visual Studio 2005. Of course, vs2005 is used here. The key to the specific version is the method. Create a Windows application named abnormalwin, as shown in:

 

Click OK. The default page is automatically created and named form1.

3. Set Related Properties

(1) set the formborderstyle attribute to none;

(2) set the backgroundimage attribute of the form to the previously prepared BMP image;

(3) set the transparencykey attribute to the background color of the bitmap file, which is white in this example.

If the color of your computer is set to less than 24 bits, the corresponding effect can be generated now. However, if the color of your computer is higher than 24 bits, no effect will be produced. What should I do? Someone tried to solve this problem in the following ways.

4. Define an image processing class bitmapregion

This category is translated by enthusiastic netizens.Article. The specific definition method is as follows:

(1) Right-click solution project abnormalwin and choose add> class, as shown in:

 

(2) In the pop-up add new project form, enter the class name bitmapregion. CS and click Add ].

(3) enter the followingCode

Replace the automatically generated code in the class file with the following code:

View code

 Using System;
Using System. Collections. Generic;
Using System. drawing;
Using System. Drawing. drawing2d;
Using System. Windows. forms;
Using System. text;

Namespace Abnormalwin
{
Public Class Bitmapregion
{
Public Bitmapregion ()
{}
/// <Summary>
/// Create and apply the region on the supplied Control
/// Create controls that support bitmap areas (buttons and forms are currently available)
/// </Summary>
/// <Param name = "control"> The control object to apply the region to control </Param>
/// <Param name = "bitmap"> The bitmap object to create the region from Bitmap </Param>
Public Static Void Createcontrolregion (Control, Bitmap bitmap)
{
// Return if control and bitmap are null
// Determine whether controls and bitmap exist
If (Control = Null | Bitmap = Null )
Return ;
// Set our control's size to be the same as the bitmap
// Set the widget size to the bitmap size.
Control. width = bitmap. width;
Control. Height = bitmap. height;

// Check if we are dealing with form here
// When the control is form
If (ControlIs System. Windows. Forms. Form)
{
// Cast to a form object
// Forced conversion to form
Form = (form) control;
// Set our form's size to be a little larger that the bitmap just
// In case the form's border style is not set to none in the first place
// When the form boundary formborderstyle is not set to none, set the form size to be slightly larger than the bitmap size.
Form. width = control. width;
Form. Height = control. height;
// No border
// No boundaries
Form. formborderstyle = formborderstyle. None;
// Set bitmap as the background image
// Set bitmap to form background image Http://www.mscto.com
Form. backgroundimage = bitmap;
// Calculate the graphics path based on the bitmap supplied
// Calculate the border of the opaque part of the bitmap.
Graphicspath = calculatecontrolgraphicspath (Bitmap );
// Apply new region
// New Application Region
Form. region = New Region (graphicspath );
}
// Check if we are dealing with button here
// When the control is a button
Else If (Control Is System. Windows. Forms. button)
{
// Cast to a Button Object
// Forced conversion to button
Button button = (button) control;
// Do not show button text
// Button text not displayed
Button. Text = "" ;
// Change cursor to hand when over button
// Change the cursor Style
Button. cursor = cursors. hand;
// Set background image of Button
// Set the background image of the button
Button. backgroundimage = bitmap;
// Calculate the graphics path based on the bitmap supplied
// Calculate the border of the opaque part of the bitmap.
Graphicspath = calculatecontrolgraphicspath (Bitmap );
// Apply new region
// New Application Region
Button. region = New Region (graphicspath );
}
}
/// <Summary>
/// Calculate the graphics path that representing the figure in the bitmap
/// Excluding the transparent color which is the top left pixel.
/// Calculate the border of the opaque part of the bitmap.
/// </Summary>
/// <Param name = "bitmap"> The bitmap object to calculate our graphics path from </Param>
/// <Returns> Calculated graphics path </Returns>
Private Static Graphicspath calculatecontrolgraphicspath (Bitmap bitmap)
{
// Create graphicspath for our bitmap Calculation
// Create graphicspath
Graphicspath = New Graphicspath ();
// Use the top left pixel as our transparent color
// Use the color at the top left corner as our transparent color.
Color colortransparent = bitmap. getpixel ( 0 , 0 );
// This is to store the column value where an opaque pixel is first found.
// This value will determine where we start scanning for trailing opaque pixels.
// First, find the X of the vertex.
Int Colopaquepixel = 0 ;
// Go through all rows (Y axis)
// Offset all rows (Y direction)
For ( Int Row = 0 ; Row <bitmap. height; row ++)
{
// Reset Value
// Reset
Colopaquepixel = 0 ;
// Go through all columns (X axis)
// Offset all columns (X direction)
For ( Int Col = 0 ; Col <bitmap. width; Col ++)
{
// If this is an opaque pixel, mark it and search for anymore trailing behind
// If it is a point that does not require transparent processing, it is marked, and then continues the calendar.
If (Bitmap. getpixel (COL, row )! = Colortransparent)
{
// Opaque pixel found, Mark Current Position
// Record current
Colopaquepixel = Col;
// Create another variable to set the current pixel position
// Create a new variable to record the current vertex
Int Colnext = Col;
// Starting from current found opaque pixel, search for anymore opaque pixels
// Trailing behind, until a transparent pixel is found or minimum width is reached
// Starting from the opacity point found, continue to look for the opacity point until it finds or reaches the image width.
For (Colnext = colopaquepixel; colnext <bitmap. width; colnext ++)
If (Bitmap. getpixel (colnext, row) = colortransparent)
Break ;
// Form a rectangle for line of opaque pixels found and add it to our graphics path
// Add the opacity point to the graphics path
Graphicspath. addrectangle ( New Rectangle (colopaquepixel, row, colnext-colopaquepixel, 1 ));
// No need to scan the line of opaque pixels just found
Col = colnext;
}
}
}
// Return calculated graphics path
Return Graphicspath;
}
}
}

5. Write a program for the load event of the form

Double-click the form. By default, the program adds a handler for the load event of the form, and then writes the following code at the cursor:

Bitmapregion = new bitmapregion (); // This is the bitmapregion. createcontrolregion (this, new Bitmap ("xyt.bmp") class for generating irregular forms and controls "));

6. Maximize, minimize, and close the form

Add three button controls at the corresponding position of the program to maximize, minimize, and close the function, and set the text of the three buttons to "port,-, X", respectively ", or you can use a nice image button by yourself. If you use the mouse to slide, press, or put down the button to achieve more advanced effects, it will be more dazzling.

(1) double-click the maximize button, and click the event handler for the auto Add button. The Code is as follows:

 
If (this. windowstate = formwindowstate. maximized) // if you have maximized this. windowstate = formwindowstate. normal; // normal window size else this. windowstate = formwindowstate. maximized; // maximize the window

(2) Add the following program code for the minimization button in the same way:

This. windowstate = formwindowstate. minimized; // minimize the window

(3) Add the following program code for the close button in the same way:

This. Close ();

7. Implement the form drag Function

First, add two member variables to the form: double-click the form interface and find the following code:

Public form1 () {initializecomponent ();}

Add the following two variable members before the Code:

Private point mouseoffset; // records the coordinates of the mouse pointer.

Private bool ismousedown = false; // record whether the mouse button is pressed

Return to the design page, find the event icon (similar to the lightning icon) in the Properties window on the right, click this button, convert it to the event interface of the form, and then add relevant event handlers for it.

(1) locate the mousedown event, double-click the event, and add the following code at the cursor:

Private void form1_mousedown (Object sender, mouseeventargs e) {int xoffset; int yoffset; If (E. button = mousebuttons. left) {xoffset =-e. x-systeminformation. framebordersize. width; yoffset =-e. y-systeminformation. captionheight-systeminformation. framebordersize. height; mouseoffset = new point (xoffset, yoffset); ismousedown = true ;}}

(2) locate the mousemove event, double-click the event, and add the following code to it:

 
Private void form=mousemove (Object sender, mouseeventargs e) {If (ismousedown) {point mousepos = control. mouseposition; mousepos. offset (mouseoffset. x, mouseoffset. y); location = mousepos ;}}

(3) locate the mouseup event and double-click the event to add the following code:

Private void form=mouseup (Object sender, mouseeventargs e) {// modify the ismousedown value in the mouse state. // make sure that the form is moved only when the left mouse button is pressed and moved. If (E. button = mousebuttons. left) {ismousedown = false ;}}

8. Program Running Effect

Press F5 to check the running effect of the program. The running effect of this example is as follows:

9. Advantages and disadvantages of this method

Irregular forms created using this method have fewer code than those written by the API, which is better for complicated and irregular forms, but has lower execution efficiency. After the program is run, he calls the bitmapregion class method to remove the background color you set a little bit, so the speed is relatively slow. If the machine runs slowly, you will see this process.

This exampleSource codeDownload: Click to download this file

 

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.