Add fun: add fun to monotonous Windows Forms applications

Source: Internet
Author: User
Tags transparent color

Microsoft. NET Framework allows you to easily create windows-based applications.Program: You only need to create a form, add controls, and connect the form to the business logic. However, such applications do not provide users with the interaction functions they really need. For example, when an important external event occurs, such applications usually do not notify users. And the window looks the same-the same warship gray form, the same standard controls, and the same feeling. Very monotonous!

With. NET Framework and GDI +, you can easily add certain styles to your applications. You can use opacity, irregular windows, notification icons, pop-up windows, different color schemes, and other elements. By carefully using these design elements, you can build a more engaging interactive experience between applications and users.

Deploy your applications

You can use a variety of simple technologies to beautify your applications. One of the techniques is to use the notification window to alert users of important events, highlight these events, and notify users of events with lower priority using methods with less interference. Many applications have applied this technology effectively. For example, MSN Messenger uses a pop-up window in the taskbar area to notify you when a friend has logged on or tried to contact you; Outlook 2003 prompts you to receive a new email through the desktop alarm notification. (These alarms also allow users to delete, Tag, or open items when they arrive .) Adding attractive forms and windows (users can use them to interact with each other) also enhances the user experience for the application. For example, you can use Windows Media Player to apply your own appearance and use a non-standard rectangular window. Obviously, you should not use all of these technologies for each application, but you can create applications that enhance user experience by using some of these technologies wisely.

I will introduce how and when to apply these technologies by modifying simple event monitor applications. The initial application displays the latest weather data for the selected city (see figure 1 ). This typical. Net-based desktop application retrieves Web Service data and displays the results in a form using a standard Windows Control. The services I use and many other Web services can be found inHttp://www.xmethods.net/In English.

Figure1Standard Application Window

This is not a very friendly application. You need to use a dedicated screen area for the weather report, and then periodically press the update button. I will enhance the application in the rest of this article to show you how to create a more engaging user experience. Finally, you will have a continuous weather Alarm Center. It will monitor specific cities and notify you when important weather changes occur, and it will break the monotonous gray application pattern. You can modify the application as notification in the taskbar) click the icon to run, provide the custom pop-up information when an event occurs, activate itself, and display its information using a custom window shape with a custom background.

Back to Top

Delete the dependency of the Main Window

The first task is to modify the application so that it no longer depends on the main form, but creates the notify (notification) icon at startup. Due to the existence of an appropriate number of bootCodeTherefore, it is best to create a new class to process application-level tasks. You will check multiple copies of the application, create the notify y icon, add menus and handlers, start the timer, start the message loop, and process some session events.

Please be sure to execute these small tasks when the application is running as the notify (notification) icon, because if it is not cleaned properly, notify (notification) is very likely to appear in the taskbar notification area at the end) icon. This makes it difficult to use the application, and may confuse users who attempt to determine which session the notify (notification) icon belongs.

To alleviate this problem, First avoid running multiple copies of the application. The common practice is to create a global mutex that specifies that the application is running (for more information about this issue, see this sectionMsdnMagazine. Net matters column ). The first instance acquires a lock on the mutex and will save the lock during the duration of the application. The subsequent copy attempts to obtain the lock, but fails, and then exits, as shown below:

 
Public shared sub main () dim extends Ingleton as new system. threading. mutex (false, _ "singleinstance weatheralert") if your Ingleton. waitone (0, false) Then application. run () mongoingleton. close () end sub

Next, enable the Windows XP topic in the application. No doubt, you have heard of enablevisualstyles, but use. NET Framework1.XYou must add additional code to enable backward compatibility (this code is no longer required for. NET Framework 2.0 ). Calling enablevisualstyles when running in the previous operating system will terminate the program, because the user will lose uxtheme. dll. You must test the new operating system before the application topic, as shown below:

Private shared sub initthemes () if (environment. osversion. platform = platformid. win32nt) _ andalso (environment. osversion. version. major> = 5) _ andalso (environment. osversion. version. minor> 0) thenif osfeature. feature. ispresent (osfeature. themes) thenapplication. enablevisualstyles () end ifapplication. doevents () end ifend sub

The main application class also creates the notify (notification) icon and runs the main message loop. Applications running without the main window are basically the same as those running applications with the main window-only two changes are required. You must change application. Run (formname) to application. Run () to start a message loop without any main form. If you have never created a main window, you do not need to create an invisible window. The second change is to process the sessionended event. If you log out of windows when the application is running, Windows will require you to exit the application by triggering the sessionended event. If you do not respond to this event, Windows assumes that the application has just encountered an error. Windows will notify your users that your application has not responded and request to terminate the application. To solve this problem, you only need to process the event and close the application. Attach the handler to the main application as follows:

Addhandler Microsoft. win32.systemevents. sessionended, _ new Microsoft. win32.sessionendedeventhandler (addressof _ applicationmain. systemevents_sessionended) will be correctly cleared in this handler: Private shared sub systemevents_sessionended (byval sender as object, _ byval e as Microsoft. win32.sessionendedeventargs) if (not _ mainwindow is nothing) Then _ mainwindow. close () _ icon. visible = falseapplication. exit () end sub

Exit code has some items that are different from standard Windows Forms applications. First, you need to check whether the main window was created before you close it. The user may not even open the main window. Then, you need to hide the notify (notification) icon. Did you disappear a program that runs as a taskbar icon and leave a highlighted taskbar icon until you try and activate it? Some developers forgot to clear the taskbar. You need to hide the notify (notification) icon before exiting the program. There is no close method for the notify (notification) icon. When the notify (notification) icon is hidden, the icon cleans itself.

Back to Top

Notify users

When you use an application as an icon, it is the time to provide feedback to the user. You can achieve this by creating a pop-up window. I do not like standard notification-I prefer notifications of other styles, such as outlook message notifications or MSN Messenger Contact logon notifications. I want to control the notification to notify users without affecting normal tasks.

After configuring Outlook 2003, a small window is highlighted in the lower-right corner of the screen when you receive an email, showing the sender and subject. You can click here to read the mail, delete the mail immediately, or set a subsequent tag. If you are busy and the email is not urgent, you can ignore the pop-up window and allow it to gradually disappear. Keep the email as unread for later reading.

Creating a similar window for the weather alarm application will make it easier for users to receive weather information updates. The notification window is displayed briefly. If you ignore the window, the window disappears. Do not create a notification form that needs to be forcibly ignored by the user. If the user is not nearby, or the user thinks the email is not important enough, the notification will disappear without interrupting the current task.

Figure2Notification box

I put the window in the lower right corner of the desktop, and the top side of the notification icon is displayed. The pop-up window should be gradually displayed and displayed for a while, and then gradually disappear. To make the window easier to use, if the user moves the mouse over the window, it will become opaque immediately and will not gradually disappear unless the user leaves the window. If you want to open the main application, you can click the pop-up window to display the main window of the application. Finally, to add some styles, you can use the gradient Paint Brush to draw the background and hide all common window boundaries (see figure 2 ). GDI + makes this operation quite simple.

Back to Top

Use GDI +

Creating transparent and non-rectangular windows requires several simple steps. First, change the form border style in the designer to none ). This operation will delete all normal non-client region objects in the pop-up window. The box, system menu, or size handle is not closed. You should also disable the "display in the taskbar" setting. You do not want the pop-up window to be displayed in the taskbar.

Transparency can be achieved using a technology called "color keying. A Color Key specifies a transparent color. When you draw a window, do not draw all pixels that match the transparent color. Be sure to select a color that is not available in normal applications. Obviously, white, black, and gray are not the best options because they are frequently used. Sour orange green or light yellow green may be better. You can use the Windows form attribute in Visual Studio. NET to set a transparent color by using the transparencykey attribute. For more information, seeColor Key,AlphaMixed value processing and transparency"Abstract bar.

After setting opacity, you must add code to draw the background. To use the rounded rectangle function implemented by GDI +, you can use the graphic path. In fact, you can use a graphic path to create any irregular shape you need.Figure3The code in describes how to create a rounded rectangle path.

The background uses another new GDI + feature-gradient paint brush. I used a linear gradient Paint Brush to create the desired background effect. First, I filled the entire background rectangle with the transparent color of acid, orange, and green, and then filled the interior rounded rectangle with a linear gradient Paint Brush (from steel blue to light blue. I used an alternative method of the onpaintbackground method to do all of this work. The alternative method is more effective than attaching the event handler to the relevant event.

To complete the drawing code, you must add a painting handler for the drawing text. It will draw messages passed to the pop-up window in its constructor. Then, you want to set the font to be consistent with the link color and activity link defined by the system. When you enter the pop-up window, change the font of the window to an underline. When the user leaves the window, the original font is restored. This will give the user the impression that the text in the pop-up window is a link.

Back to Top

Gradually display and gradually disappear

The next step is to add the timer and handler to update the opacity of the pop-up window. In the designer, add a timer and set the initial opacity of the pop-up window to 0%. Increases opacity when a timer event is triggered (I chose to increase by 0.05 ). When the opacity reaches 1, reset the timer to be triggered within 3 seconds, so that the user has time to view the pop-up window. Then, set the timer to a small interval to reduce the opacity of each trigger. Close the window when the opacity reaches 0.

You must add a handler to stop the process from gradually displaying or gradually disappearing when you move the mouse over the pop-up window. Of course, when you leave this window, you must restart and gradually disappear the process. There is only one issue to be aware. The close box (see figure 2) is a subwindow. When you move the cursor over the close box, the mouseleave message is displayed in the main window.

In addition to the mouse entry and mouse exit methods in the pop-up window, you must also add an event handler for all subwindows in the pop-up window. Although you do get the entry and exit events when the user moves between the close box and the parent pop-up window, the mouseleave message is not obtained from one window before obtaining other mouseenter events. This means that the status error cannot be caused when you move from one window to another. When a user interacts with a pop-up window, the window does not disappear.

Before you exit the window, you must define the behavior of the window when you receive multiple updates. In this example, I used a simple method: if a second notification occurs when the pop-up window is displayed, ignore it. Commercial applications use different methods. Outlook 2003 creates a series of pop-up windows, one for each email. MSN Messenger stacks the pop-up window on the screen until it reaches the top of the desktop. This example does not generate enough interesting notifications to this extent.

Back to Top

Design the appearance of the application

Apply some styles to the main window (see figure 4 ). To achieve the effect, you must create a background image. Any position you want to make transparent should be drawn in transparent color. In my example, I selected the background color as orange-green. Set the background image to a new bitmap, and set the border style of the form to none (none). This is basically done. The problem is that when the bitmap color depth is different from the monitor color depth, some graphics cards prevent transparency from working (for more information, see the knowledge base ).Article822495BUG: The transparencykey property is not valid tive for Microsoft Windows Forms if the color depth of the monitor is set to a value that is greater than 24-bit(English ). To solve this problem, you must set the background bitmap to transparent. The onload substitution method shown in the following code can be used to perform this operation.

 
Protected overrides sub onload (byval e as eventargs) dim bitmapbg as bitmap = _ ctype (backgroundimage, bitmap) bitmapbg. maketransparent (bitmapbg. getpixel (0, 0) transparencykey = bitmapbg. getpixel (0, 0) mybase. onload (e) End sub

After the image is updated, you must update the transparency key to match the changed value of the pixel.

Figure4Add a style to the Main Window

Then, you need to modify the controls so that they are transparent and better displayed in the background. I selected a yellow font to distinguish it from the background image. You can modify the background color in the designer or code to system. Drawing. color. Transparent. The background image is displayed through the control (see figure 5 ).

Figure5Background Image Display Mode

Finally, it will help you add a mechanism to move the main window around the screen. Because there is no longer a title bar, you can move the window by clicking the left mouse button at any position of the visible form and dragging the window from one position to another. If you drag a window, the mousemove method moves the window:

 
Protected overrides sub onmousemove (byval e as mouseeventargs) If _ ismoving thenlocation = new point (location. X + E. x-xoffset, location. Y + E. y-yoffset) end ifmybase. onmousemove (e) End sub

This method is useful unless the user clicks the mouse in one of the subwindows (the created window for displaying weather information. To make it take effect, you must create a mouse processing program that specifies the movement operation when you click the mouse button in a subwindow. But this is not useful for all subwindows-you still need to link the button and the default behavior of the close box. The same method can handle all the mousedown events of any other sub-controls, as shown below:

Private sub child_mousedown (byval sender as object, _ byval e as system. windows. forms. mouseeventargs) handles _ labelairpressure. mousedown, labeldewpoint. mousedown, _ labelhumidity. mousedown, labellocation. mousedown, _ labelskyconditions. mousedown, labeltemperature. mousedown, _ labelvisibility. mousedown, labelwind. mousedownif (E. button = mousebuttons. left) then_ismoving = truexoffset = E. xyoffset = E. yend ifend sub

Add the close box and link button to get the latest weather information.

Back to Top

Summary

Highlight the applications that need to interact with users in different ways, but not over. Since the standard appearance is already familiar to the user, if you break this mode, the reason must be sufficient. Because too many applications occupy the space in the system taskbar, do not perform this operation unless it is indeed the best way for applications to interact with users. Otherwise, use other methods to promote your application.

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.