Building Desktop Apps
Richard Harris
DevOps, Online & Mobile at TD Bank Group #devops #agile #cloud #java #js #csharp
Contents
1. Introduction
- Universal Windows Platform (UWP)
- Windows Presentation Foundation (WPF)
- Windows Forms
- Other app platforms
2. Further Resources
- Framework Comparisons
- Videos
- Wikipedia
3. Review of Windows Forms
- Where WinForms Is Still Useful
- .NET & Visual Studio
- Exploring Windows Forms Controls (including Top Controls)
- Basic WinForms Code Samples
- Menus, Methods, Helper Classes, and Multiple Forms
- Setup
- Tips and Techniques (i.e. the TODO: Statement, Using DataSets and XML, etc.)
Introduction
Windows Forms, or WinForms, was introduced together with .NET 1.0 in 2002. It was the first desktop UI technology for .NET. It has been succeeded by WPF and UWP. In 2006, Microsoft introduced .NET 3.0, which included the Windows Presentation Foundation or WPF. WPF brought us XAML, the Extensible Application Markup Language. The combination of a .NET language (e.g. C# or VB.NET) for logic and XAML for markup continued in Windows 8 and Windows 10. The latest desktop UI framework from Microsoft, the Universal Windows Platform or UWP, is also based on XAML.
Universal Windows Platform (UWP)
UWP is the leading-edge platform for Windows 10 applications and games. It's a highly customizable platform that uses XAML markup to separate UI (presentation) from code (business logic). UWP is suitable for desktop applications that require a sophisticated UI, styles customization, and graphics-intensive scenarios. UWP also has built-in support for the Fluent Design System for the default UX experience and provides access to the Windows Runtime (WinRT) APIs. By adopting Fluent, UWP automatically supports common input methods such as ink, touch, gamepad, keyboard, and mouse.
Not only can you use UWP to create desktop applications for Windows PCs, but UWP is also the only supported platform for Xbox, HoloLens, and Surface Hub applications. UWP is our newest, leading-edge application platform.
UWL and .NET Native
- Managed UWP applications are compiled with .NET Native, versus C++/WinRT and C++/CX for Native UWP applications.
- .NET Native is a precompilation technology for building and deploying Windows apps that is included with Visual Studio 2015 and later versions. It automatically compiles the release version of apps that are written in managed code (C# or Visual Basic) and that target the .NET Framework and Windows 10 to native code.
- Typically, apps that target the .NET Framework are compiled to intermediate language (IL). At run time, the just-in-time (JIT) compiler translates the IL to native code. In contrast, .NET Native compiles Windows apps directly to native code.
- .NET Native includes in the final app assemblies only the implementation code that is actually invoked by the app. This particularly affects code in third-party libraries and in the .NET Framework Class Library. As a result, an application no longer depends on either third-party libraries or the full .NET Framework Class Library; instead, code in third-party and .NET Framework class libraries is now local to the app.
For more information about UWP, see the following articles:
Textbooks:
- Developing Windows 10 Applications with C#
- Programming Windows 10 Via UWP: Learn To Program Universal Windows Apps For the Desktop
- XAML Unleashed
Windows Presentation Foundation (WPF)
WPF is the established platform for managed Windows applications with access to .NET Core or the full .NET Framework, and it also uses XAML markup to separate UI from code. This platform is designed for desktop applications that require a sophisticated UI, styles customization, and graphics-intensive scenarios. WPF development skills are similar to UWP development skills, so migration from WPF to UWP apps is easier than migration from Windows Forms.
For more information about WPF, see the following articles:
- Getting started (WPF)
- Create your first app (.NET Core)
- Create your first app (.NET Framework)
- Migrate WPF apps to .NET Core
- API reference (.NET)
- Samples
Textbooks:
- WPF 4.5 Unleashed
- Pro WPF 4.5 in C#: Windows Presentation Foundation in .NET 4.5
- Programming WPF: Building Windows UI with Windows Presentation Foundation
- Windows Presentation Foundation Development Cookbook: 100 recipes to build rich desktop client applications on Windows
Windows Forms
Windows Forms is the original platform for managed Windows applications with a lightweight UI model and access to .NET Core or the full .NET Framework. It excels at enabling developers to quickly get started building applications, even for developers new to the platform. This is a forms-based, rapid application development platform with a large built-in collection of visual and non-visual drag-and-drop controls. Windows Forms does not use XAML, so deciding later to extend your application to UWP entails a complete re-write of your UI.
For more information about Windows Forms, see the following articles:
- Getting started with Windows Forms
- Create your first Windows Forms app
- Tutorial: Create a picture viewer
- API reference (.NET)
- Enhancing Windows Forms apps
Microsoft Docs | Windows Forms
- Windows Forms
- Windows Forms controls
- Controls to Use on Windows Forms
- System.Windows.Forms Namespace
- Form Class
3rd Party Windows Forms Components (i.e. Professional User Interface)
- DotNetBar - Metro UI, Office 2010, 2007 Ribbon Controls, BubbleBar, Navigation Pane, Schedule, Side-Bar, SideNav Menu, Tabbed Form, Touch Keyboard, and more
- DotNetBar - Video Tutorials
- Intragistics - Windows Forms UI Controls
- Infragistics - Sample Application - Windows Forms Inventory App
Other app platforms
Progressive Web Apps (PWAs)
PWAs let developers package their website code so it can be installed and run like an application on Windows 10 PCs. For more information, see Progressive Web Apps.
Xamarin
Use Xamarin to build cross-platform applications for Windows 10 that can also run on iOS and Android. For more information, see Xamarin.
Platform Uno
Build native mobile (Android & iOS), desktop and WebAssembly applications from a single codebase with C# and XAML. It is open source and professionally supported. For more information, see Platform Uno.
Reference
Further Resources
Framework Comparisons
- Which .NET framework for Windows: UWP, WPF or Windows Forms?
- Best Frameworks for Desktop Application Development
- 5 Best Frameworks for Desktop Application Development
Videos
- Get started with your first Universal Windows app
- Windows Presentation Foundation (WPF) Application Development
- Modernizing Desktop Apps Part 1
- Modernizing Desktop Apps Part 2
Wikipedia
- Universal Windows Platform
- Windows Presentation Foundation
- Extensible Application Markup Language
- Windows Forms
Like This Article? Read More Of Richard's Content On LinkedIn
Review of Windows Forms
- Where WinForms Is Still Useful
- .NET & Visual Studio
- Exploring Windows Forms Controls (including Top Windows Forms Controls): Label, LinkLabel, Button, TextBox, CheckBox, RadioButton, GroupBox, PictureBox, ListBox, ComboBox, MonthCalendar, OpenFileDialog, SaveFileDialog
- Basic WinForms Code Samples
- Menus, Methods, Helper Classes, and Multiple Forms
- Setup
- Tips and Techniques
Where WinForms Is Still Useful
Many assume WinForms is dead. However, many companies still have WinForms applications that are important to their daily operations. You might think this situation is comparable with the many COBOL applications running out there, but Developers continue to maintain, improve, and port these applications. WinForms is not as commonly used for creating new applications anymore though.
But there is something WinForms does better than WPF or UWP: ease of development. WinForms is great for making a quick prototype of an application. The learning curve is a lot less steep than it is for WPF or UWP. The UI editor in Visual Studio is much better. No need to struggle with the often complex syntax of XAML, just drag and drop your controls and wire it up to your code. If you want to focus as little as possible on your UI code, WinForms is actually a better choice than WPF or UWP. WinForms allows you to focus on your business logic, and spend less time developing your UI.
.NET & Visual Studio
In A Nutshell
- At the heart of Microsoft's .NET strategy is the .NET Framework. This is essentially a runtime that runs .NET programs and provides common functionality, plus manages much of the standard "plumbing" as well.
- The .NET Framework runs .NET applications, it handles program memory, and provides a common base functionality for programmers to use.
- Microsoft Visual Studio .NET is a product that allows you to create programs to run on the .NET Framework. Among the langues you can use in Visual Studio .NET, we find Visual C#, Visual C++, and Visual Basic.
- You can create many different types of projects in Visual Studio.
- To create a regular Windows application, you typically: draw controls onto your form(s), change control properties using the Properties window, and add code (i.e. Form Event Handlers & custom classes) to stick it all together.
- Compiling your application consists of selecting Build > Build. This generates an executable file with .exe extension) in your project's Bin sub-folder. This project will run on any machine containing the .NET Framework.
- Compiled executable files produced by Visual Studio actually contain raw MSIL (Microsoft Intermediate Language) and metadata (descriptive information about your code). When an EXE file is run for the first time on a machine, this MSIL code is optimized for the computer, full compiled, and then locally cached for its next use. This is all handled automatically by a part of the .NET Framework called the Common Language Runtime (CLR).
- Namespaces are a logical way of organizing functionality. You can liken a namespace to a digital filing cabinet for classes and functions. You can even "build your own" application namespaces if you wish.
- The most important namespaces you'll find in the .NET framework is System, which links to objects dealing with everything from accessing an SQL Server database to manipulating files.
Visual Studio
- New Project > Windows Application
- Start | F5
- View Event Handlers via: View Code > Class Name > Method
- Right-click on project in Solution Explorer > Properties > Startup Object
Debugging
- F9 - Toggle Breakpoint. When this line of code is encountered in your application, you'll be returned to the code window and allowed to step through it line by line.
- F5 - Start Application (w/ Debug mode selected).
- F8 - Step Through each line of code.
- Note: While in break mode, Hover your mouse over the properties of you use in the code.
Exploring Windows Forms Controls
In A Nutshell
- Every control you add to a form has a Name property, which is how you refer to it in code.
- Most controls include a mixture of methods and properties.
- Certain controls don't have a visible form size to them. However, you can still change their properties and access them in code by referencing their name. Invisible controls appear in a control bar underneath your form. Examples of such controls include OpenFileDialog and Timer.
- Your form itself can be treated as a regular control and contains its own methods and properties. To refer to your own form in code, use the this keyword.
- Most controls - and your form itself - support events. These allow you to add code in a subroutine that runs whenever a particular event occurs, such as a click or selection change.
- One way way to respond to an event is Design View > Select Control > Properties Window > Events.
- Another way to respond to an event is to select a Class or Method name using the drop-down boxes in the code window. To enter code to respond to a form event, you need to select "(Base Class Events)" as the Class entry.
Key Concepts
- Forms
- Controls
- Properties
- Methods
- Events
Top Windows Forms Controls
Label - Displays a chunk of text. Commonly used for descriptions or output.
- Key properties: Text, Font, ForeColor, TextAlign
- Key methods: BringToFront
- Key events to play with: Click, MouseMove
- Sample code:
lblWelcome.Text = Welcome, User!";
LinkLabel - Has the look and feel of a hyperlink you'd find on a web page, but instead, clicking this link will run a chunk of code in your program.
- Key properties: ActiveLinkColor, Cursor, LinkColor, Text LinkBehaviour
- Key methods: Show, Hide
- Key events to play with: LinkClicked
- Sample code:
lnkCompanySite.LinkBehavior = LinkBehavior.HoverUnderline;
Button - You click it; it does stuff (fire event handler).
- Key properties: FlatStyle, Text, TextAlign, Image, ImageAlign
- Key methods: PerformClick, Focus
- Key events to play with: Click, MouseMove
- Sample code:
btnOK.PerformClick();
TextBox - A box that holds text - can display information, hold data that the user types in, plus even look like a password input box.
- Key properties: ScrollBars, Font, Text, MaxLength, MultiLine, PasswordChar, TextAlign
- Key methods: SelectAll, Clear, Undo, ClearUndo, AppendText, Focus, Cut, Copy, Paste, Contains
- Key events to play with: TextChanged, Enter, KeyDown, KeyPress, KeyUp, Leave
- Sample code:
txtData.AppendText(" My Text "); txtPhone.Text = "555-555-5555";
CheckBox - You can check it or not check it. Great for getting the user to give you a yes or no answer.
- Key properties: CheckState, Text
- Key methods: sendToBack
- Key events to play with: CheckChanged
- Sample code:
chkGener.SendToBack();
RadioButton - When you need to give the user a short list to choose from, radio buttons are a heaven-send. Add as many as you like, but remember that only one can be selected at a time. To use multiple sets of Radio Button controls over a form, put each inside its own GroupBox.
- Key properties: Checked, Text
- Key methods: PerformClick
- Key events to play with: CheckChanged
- Sample code:
rapOption1.Checked = true;
GroupBox - A box with a caption somewhere at the top. You can also put other controls inside the box and they stick with it when moved about.
- Key properties: BackgroundImage, Text, Visible
- Key methods: Show, Hide
- Key events to play with: MouseMove
- Sample code:
grpDetails.Visisble = false;
PictureBox - This is a box that holds a picture. In the real world it is useful for holding logos.
- Key properties: Image, SizeMode, Anchor
- Key methods: BringToFront
- Key events to play with: Click
- Sample code:
picAuthor.Image = New Bitmap(ofdImage.FileName);
ListBox - It typically displays a short bunch of items, ready for the user to select one. If you change the right properties, you can allow the user to select multiple items form the same list.
- Key properties: MultiColumn, SelectionMode, Sorted, Items
- Key methods: ClearSelected, FindString, FindStringExact
- Key events to play with: SelectedIndexChanged, SelectedValueChanged, TextChanged
- Sample code:
lstItems.ClearSelected();
ComboBox - When you need to display a longer bunch of items for the user to select from, this control steps onto the scene. It presents a drop-down box of items for the user to select from. It's great for holding longer lists.
- Key properties: DropDownStype, Text, MaxDropDownItmes, Sorted, Items, SelectedText
- Key methods: BeginUpdate, EndUpdate, ResetText
- Key events to play with: SelectedIndexChanged, SelectedValueChanged, TextChanged
- Sample code:
cboUsers.ResetText();
MonthCalendar - It's a calendar, that allows you to select dates and ranges.
- Key properties: FirstDayOfWeek, MaxDate, SelectionRange, ShowToday, ShowTodayCircle, ShowWeekNumbers
- Key methods: AddAnnuallyBoldedDate, AddBoldedDate
- Key events to play with: AddMonthlyBoldedDate, RemoveBoldedDate, SetDate, SetSelectionRange
- Sample code:
calDate.AddBoldedDate(#5/20/2002#);
OpenFileDialog - It's invisible, but you use it in your code just like a regular control by dragging it onto your form.
- Sample code (i.e. button click event):
ofdImage.Filter = "Picture Files|*.bmp;*.jpg;*.jpeg;*.gif;*.ico"; ofdImage.ShowDialog();
The SaveFileDialog - Allow Users to specify their own filename.
The Form Control - Actual Windows Form
- Key properties: Name, Text
- Key methods: Show
Basic WinForms Code Samples
var MyResult as DialogResult; MyResult = MessageBox.Show("Continue","MyApp",MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if(MyResult == DialogResult.Yes) MessageBox("Operation accepted!"); else if(MyResult == DialogResult.Cancel) MessageBox.Show("Operation aborted!");
MessageBox.Show("[string]"); MyString = InputBox("[Question?]"); Application.Exit(); Process.Start("https://www.microsoft.com");
Menus, Methods, Helper Classes, and Multiple Forms
In A Nutshell
- You can graphically design menus in your application by adding the MenuStrip control to your form. You could then click on the Type Here box and type "&File", then add the following entries under the File heading: &New, &Open, - (adds a horizontal line), and E&xit.
- Every menu entry you create using the MenuStrip control is actually an individual ToolStripMenuItem control, each with its own click and select events. A key property of ToolStripMenuItem is ShortcutKeys (i.e. Ctrl + N).
- To add a new form to your project, select Project > Add Windows Form from the menu.
- Forms are classes and should be treated in the same way as regular classes in the .NET Framework. Every Windows form inherits a .Show method, which displays the form to the user.
- Helper / Utility classes are a holding point for variables, objects, and methods. To add a class to your project, select Project > Add Class from the menu.
Key Concepts
- Menus
- Multiple Forms
- Methods
- Helper / Utility Classes (class WinFormUtilities)
Multiple Forms
- Add > Windows Form
- Snippet:
var MyCalc = new CalculatorForm(); MyCalc.Show();
- Tip: To avoid multiple instances of a Form, rather than have your new form object created in a method (i.e. Event Handler), have it declared as a form-level variable.
MDI
- You can have multiple forms open inside one big container form.
- MDI stands for Multiple Document Interface. It's where you have one "master" form and any number of "child" forms within it.
- To set your "master" form, change its IsMdiContainer property to True. Then, to display a child form within your master form, run code similar to the following, setting the MdiParent to your current Form object:
var myForm = new Form2() myForm.MdiParent = this; MyForm.Show();
- You can get a direct reference to the currently active MDI child form, by referencing the ActiveForm property of your master Form object. For example:
Form myForm; myForm = this.ActiveForm;
- You can also arrange your children windows by using the LayoutMdi method of your master Form object. You can set this to cascade your child windows, tile them horizontally or vertically, or arrange them as icons. Here's an example:
this.LayoutMdi(MdiLayout.TileHorizontally);
Code Sample
Form1 objMyForm = new Form1(); objMyForm.Show();
Helper / Utility Class Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace DemoWinForm { public class WinFormUtilities { // Reset Form /* Sample Usage: public void ResetForm() // Used in Form1 btnNew_Click & mnuFileNew_Click { WinFormUtilities.ResetAllControls(this); // reset form controls // reset form variables... } */ public static void ResetAllControls(Control form) { foreach (Control control in form.Controls) { // Tip: The Tag property allows for user-defined data to be associated with the object (Form Control). // So for an example, we could mark some controls as "skip" and then check for this in the code bellow. if (control is GroupBox) { ResetAllControls(control); } else if (control is TextBox) { TextBox textBox = (TextBox)control; textBox.Text = null; } else if (control is ComboBox) { ComboBox comboBox = (ComboBox)control; if (comboBox.Items.Count > 0) comboBox.SelectedIndex = 0; } else if (control is CheckBox) { CheckBox checkBox = (CheckBox)control; checkBox.Checked = false; } else if (control is CheckedListBox) { CheckedListBox checkListBox = (CheckedListBox)control; checkListBox.ClearSelected(); for (int i = 0; i < checkListBox.Items.Count; i++) checkListBox.SetItemCheckState(i, CheckState.Unchecked); } else if (control is ListBox) { ListBox listBox = (ListBox)control; listBox.ClearSelected(); } else if (control is RadioButton) { RadioButton radioButton = (RadioButton)control; radioButton.Checked = false; } else if (control is DateTimePicker) { DateTimePicker dateTimePicker = (DateTimePicker)control; dateTimePicker.Value = DateTime.Now.Date; } } } // Can be used in Form's CheckBoxListBox Event Handlers - Allow only one checked ListItem /* Sample Usage: private void checkedListBox_SingleItemCheck(object sender, ItemCheckEventArgs e) { WinFormUtilities.CheckedListBoxSingleItem(sender, e); } */ public static void CheckedListBoxSingleItem(object sender, ItemCheckEventArgs e) { var clb = (CheckedListBox)sender; // Only allow 1 item to be checked if (e.NewValue == CheckState.Checked) for (int ix = 0; ix < clb.Items.Count; ++ix) if (e.Index != ix) clb.SetItemChecked(ix, false); } // Set CheckedListBox Item to checked if match found public static void SetItemChecked(CheckedListBox clb, string item) { int index = clb.Items.IndexOf(item); if (index >= 0) clb.SetItemChecked(index, true); } } }
Setup
In A Nutshell
- The first step in creating a setup program for your application is to add a setup project to your solution. To add a new setup project to your solution, choose File > Add Project > New Project > Other Project Types > Visual Studio Installer > Setup Project.
- To add the output from your application to this setup project, select Project > Add > Project Output and select the Primary Output from your project, clicking on OK when finished. When finished, build your solution as normal.
- Beyond creating a standard installation, you can do much more with setup projects. To view the advance editing screens choose View > Editor and select one of the menus.
Building a Setup Program
- You could just copy and paste EXE & alongside any separate DLLs you've referenced to deploy your application (i.e. XCOPY deployment). But what are your other options? Well, you could relatively easily create a setup program: simply add a setup project to your existing solution, tell Visual Studio which files it should install and any shortcuts it needs to make, and then run a build. Note, you may need to set Setup Project > Build to True in Solution's Configuration Manager.
- Tell the setup project what it actually needs to install by right-clicking on your Setup Project in the Solution Explorer and selecting Add > Project Output. From the dialog box that appears, select Primary Output for your project and click on OK. You should be looking at the File System view. If not, right-click on the Setup Project in the Solution Explorer, choosing View > File System. Click on the Application folder. You should see the primary output from your main project.
- To create a shortcut to your core EXE file, right-click on "Primary Output from MyApp(Active)" and select "Create Shortcut to Primary output...".
- If you prefer to have your own sub-folder in the user's Start Menu - which is particularly useful if you have extra files you want to create shortcuts for - then right-click on the User's Programs Menu folder and select Add > Folder - then move your shortcut into the new folder.
- Try right-clicking on your Setup Project in the Solution Explorer and selecting Properties. Here you can specify the output filename of your setup project; you can also select to optimize your setup package for size, ensuring smaller downloads for your clients.
Key Setup Program properties:
- Add/RemoveProgramsIcon
- Author
- Description
- Manufacturer
- ManufacturerUrl
- Title
Customize Your Setup (via View > Editor or right-click on Setup Project > View):
- File System (Application Folder, User's Desktop, User's Programs Menu) - Allows you to define where your application is installed, add any extra files, and incorporate shortcuts.
- Registry - Allows you to specify any registry keys you want to insert upon installation.
- File Types - Allows you to associate a particular file extension with your application, automatically.
- User Interface - Give you more control over what the user sees, allowing you to change items such as the banner bitmap, welcome messages, and copyright text.
- Custom Actions - Allows you to further personalize the experience.
- Launch Conditions - Allows you to further personalize the experience.
Note: If you want to have a "skeleton" setup program that downloads the Windows Installer and your application from the Net as and when required, use the Bootstrapper option by providing an Installation URL.
Download Visual Studio Extensions:
- Tools Extensions - Visual Studio
- Microsoft Visual Studio 2015 Installer Projects - Visual Studio Marketplace
Tips and Techniques
This section covers the following tips:
- Resizing Controls at Runtime
- Changing Your Window State
- Using Visual Inheritance
- Typing the TODO: Statement
- Changing the Tab Order
- Customizing the Cursor
- Creating a Number-Only Text Box
- Ending Your Application
- Using DataSets and XML
- Creating Your Own Icons
- Highlighting Form Errors
Resizing Controls at Runtime
- When the user resizes your Windows form at runtime, all your controls will stay in place by default. They will not automatically resize with the form. You can change this behaviour by editing the Anchor property of a control.
- The Anchor property determines which of a form's sides will stretch with that control. After the default, the most common setting for this property is "Top, Bottom, Left, Right" - meaning that the control will stretch with all sides of your form, behaving like the majority of resizable Windows applications.
- The Dock property of a control is also useful when positioning and resizing controls. It allows you to dock a control to a particular side of a form and stick with that side, regardless of how the form is resized. To set this, simply select a new region via the Dock property drop-down.
Changing Your Window State
- Two main properties determine the state of your Windows form when it loads: StartPosition and WindowState. The most common StartPosition property value is CenterScreen.
- The WindowState property controls whether your form is maximized, minimized, or left as in design mode. You can change this in the Property window or in code, for example:
this.WindowState = FormWindowState.Maximized
Using Visual Inheritance
- Visual inheritance allows you to create one "master" form, then have other Windows forms inherit its layout and code. For example, you might create one master form for your application wizard, then add further wizard forms that automatically inherit its appearance and functionality, customizing each as appropriate.
- To use visual inheritance, first design and code your master form, then build your application (Ctrl+Shift+B). Next, select Project > Add New Item > Visual C# Items > Windows Forms > Inherited Form. Then, further customize this form to meet your needs.
Typing the TODO: Statement
- The Task window in Visual Studio is a great way of keeping track of tasks that are related to your project.
- You can add your own comments to the Task list, using the TODO keyword. To use this feature, simply add a comment to your code that starts with the TODO keyword. It will automatically be added to your existing Task list. For example:
// TODO: Rewrite function
- To view the Task list, select View > Task List from the menu.
Changing the Tab Order
- In Windows forms, the tab order determines which controls receive the focus and in what order as your user presses the Tab key.
- To stop a control from receiving the focus when your user hits the tab key, set the TabStop property to False. To change its tab order, alter the TabIndex property to a value starting at 0, where 0 is the first control to receive the focus.
- One simple way to set the tab order is to select View > Tab Order from the menu, then select your controls in the proposed tab order. The TabIndex property will automatically set for you.
Customizing the Cursor
- If you have a long operation running, you might want to temporarily set the current Cursor property to wait cursor in code, then revert to the default afterwards, as so:
Cursor.Current = Cursors.WaitCursor; // do processing here Cursor.Current = Cursors.Default;
Creating a Number-Only TextBox
- In some instances, you only want to allow the user to enter a numeric value in a TextBox control on your Windows form. To do this, you need to write code to check every key press in that TextBox. Here's a chunk of sample code you could add underneath a TextBox KeyPress event to do this:
private void txtNumberOnly_KeyPress(object sender, KeyPressEventArgs e) { if ((int)e.KeyChar < 48 || (int)e.KeyChar > 57) // '0' (ascii - 48) to '9' (ascii - 57) { // Cancel non-numeric characters e.Handled = true; } }
Ending Your Application
- To quit your application, you should run the Exit method of the Application object. For example:
Application.Exit()
Using DataSets and XML
- Because DataSets typically hold structured data, they're an obvious target for working XML documents. To help simplify the process, two key methods are incluced with the DataSet component to automatically handle XML for you: WriteXml and ReadXml.
- To use these simply call the methods as so, passing in a relevant filename:
DataSet MyDataSet = new DataSet(); MyDataSet.WriteXml(@"c:\temp\abc.xml"); MyDataSet.ReadXml(@"c:\temp\xyz.xml");
Creating Your Own Icons
- You can create your own icons in Visual Studio by selecting Project > Add New Item from the menu, then choosing Icon File and clicking Open.
- To change a Windows form icon, click the ellipsis next to its Icon property in the Properties window. Then, navigate to your project folder and select the Icon file (*.ico) that you added to your project.
Highlighting Form Errors
- The ErrorProvider control provides a great way of providing visual user feedback. You can use it to add a flashing error icon next to a control, along with a Tool Tip describing the error.
- Sample:
// Prerequisite: Add ErrorProvider control object to Form int n = 0; try { n = int.Parse(txtParseNumber.Text); MessageBox.Show("Your #: " + n); errorProvider1.SetError(txtParseNumber, ""); } catch { errorProvider1.SetError(txtParseNumber, "Please enter a number."); }