Stuart Celarier, Fern Creek, www.ferncrk.com .NET/XML Consultant, course author, trainer Please email comments and corrections to faq@ferncrk.com. The editor wishes to gratefully acknowledge contributions to this document from George Shepherd's Windows Forms FAQ on syncfusion.com. Updated January 24, 2005, 6:12 PM Pacific Standard Time Windows Forms FAQ PagesWindows Forms | Controls and Components (General) | Controls and Components (Specific) | Data | .NET Framework | Tools | Windows Forms 2.0 Contents of this Page Key to Finding Answers in the Windows Forms FAQ Topics in this FAQ are organized into a series of pages. This key is your guide to the organization of topics into pages and the relations between them. Windows Forms Windows Forms covers Windows Forms applications on the .NET Framework 1.0 and 1.1, the System.Windows.Forms.Form class, common dialogs, and some general reading recommendations. Key relationships. A Form is a Control, a Control is a Component: see Controls and Components (General) for information that applies to Forms but isn't specific to just Forms. Related sections. See Tools for information about developing and debugging Windows Forms using Visual Studio and other tools and utilities. See .NET Framework for information outside of the System.Windows.Forms namespace that is relevant to Windows Forms applications. See Windows Forms 2.0 for information about Windows Forms using Visual Studio 2005 and .NET Framework 2.0. Controls and Components (General) Controls and Components (General) covers the System.Windows.Forms.Control and System.ComponentModel.Component classes, including their appearance and behavior, and design-time issues. There is a section on hosting Controls in Internet Explorer. Key relationships. A Control is a Component. A Form is a Control. Related sections. See Controls and Components (Specific) for specific controls and components, i.e., classes derived from Control and Component. See Data for data sources and data binding as they apply to all Controls. See Controls and Components (Specific) for data sources and data binding as they apply to specific Controls. Controls and Components (Specific) Controls and Components (Specific) covers classes derived from System.Windows.Forms.Control and System.ComponentModel.Component. Key relationships. A Control is a Component. A Menu is a Component; a ContextMenu is a Menu. A ToolTip is a Component, but most ToolTip questions relate to specific controls. Exceptions. A Form is a Control, but see Windows Forms for information about Forms. A CommonDialog is a Component, but see Windows Forms for information about CommonDialogs. Related sections. See Controls and Components (General) for information that applies to all Controls and Components. See Data for data sources and data binding as they apply to all Controls. Data Data covers databases, data sources, the DataSet class and data binding as they apply to all Controls. Related sections. See Controls and Components (Specific) for data binding to specific controls. .NET Framework .NET Framework covers Common Language Runtime (CLR) features, the Framework Class Library (FCL) outside of the System.Windows.Forms namespace, and issues that apply to all .NET Framework applications not specifically to Windows Forms applications. Related sections. See Windows Forms, Controls and Components (General) and Controls and Components (Specific) for information about the System.Windows.Forms namespace and Windows Forms applications. See Data for information about the System.Data namespace and data binding. See Tools for information about developing and debugging software on the .NET Framework using Visual Studio and other tools and utilities. See Windows Forms 2.0 for information about .NET Framework 2.0 related to Windows Forms 2.0 applications. Tools Tools covers Visual Studio and other tools and utilities used to develop and debug Windows Forms applications and other .NET Framework applications generally. Related sections. See the Design-Time section of Controls and Components (General) for information about developing controls to work with the Designer and working with controls at design-time. See Data for information about data binding in the Designer. Windows Forms 2.0 Windows Forms (System.Windows.Forms.Form) General Where can I find a good, succinct introduction to Windows Forms? See Windows Forms: A Modern-Day Programming Model for Writing GUI Applications by Jeff Prosise from MSDN Magazine, February 2001. Also see Using the Microsoft .NET Framework to Create Windows-based Applications by Shawn Burke in the MSDN Library. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I set the default button for a form? Set the form's AcceptButton property. You can do this either through the designer, or through code such as form1.AcceptButton = button1;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I return values from a form? Add public properties to your form. Then these properties can be accessed by any object that creates an instance of your form. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I work with multiple forms since that's different from VB6? Check out ` by Duncan Mackenzie in the MSDN Library. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I print a form? Unfortunately, there is not a very easy way to print a form. You may implement this function with the steps below: 1.Add a print function to your application. To do this, you should add a PrintDocument component to your application. Please drag a PrintDocument from the tool box to your form. After that, you should create a PrintDialog and add the code to print the document. private void buttonPrint_Click( object sender, EventArgs e ) { PrintDialog printDialog1 = new PrintDialog(); printDialog1.Document = printDocument1; DialogResult result = printDialog1.ShowDialog(); if ( result == DialogResult.OK ) printDocument1.Print(); }
For detailed information about print framework, please see Windows Forms Print Support (Visual Studio) in the MSDN Library. 2. Draw the form when printing. This step is a little complex. You should handle the PrintPage of the printDocument1 and draw the form to the printer device. In the event you may copy the form to an image and then draw it to the printer device. using System.Drawing.Printing;
private void printDocument1_PrintPage( object sender, PrintPageEventArgs e) { Graphics graphic = CreateGraphics(); Image memImage = new Bitmap( Size.Width, Size.Height, graphic ); Graphics memGraphic = Graphics.FromImage( memImage ); IntPtr dc1 = graphic.GetHdc(); IntPtr dc2 = memGraphic.GetHdc(); BitBlt( dc2, 0, 0, ClientRectangle.Width, ClientRectangle.Height, dc1, 0, 0, 13369376 ); graphic.ReleaseHdc( dc1 ); memGraphic.ReleaseHdc( dc2 ); e.Graphics.DrawImage( memImage, 0, 0 ); }
The above referenced the article Screen Capturing a Form in .NET - Using GDI in GDI+" by Michael Gold on C# Corner. 3. Declare the API function. Please note the BitBlt function used in Step 2. It is an unmanaged function. You should use DllImport attribute to import it to your code. Although, this is the Step 3, you may perform this step any time. using System.Runtime.InteropServices;
[ DllImport( "gdi32.dll" ) ] private static extern bool BitBlt( IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, System.Int32 dwRop ); Lion Shi, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I display the PrintPreview as a maximized window and control its zooming? You can use the WindowState property of the PrintPreviewDialog class to bring the PrintPreview maximized. To handle zooming, the PrintPreviewDialog has a property, PrintPreviewControl. PrintPreviewControl owns a Zoom property that allows you to set the zoom factor of the PrintPreview. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I capture a bitmap of a form? You can P/Invoke the BitBlt function from gdi32.dll to handle this problem. using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Windows.Forms;
class CustomForm : Form { [ DllImport( "gdi32.dll" ) ] private static extern bool BitBlt( IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, Int32 dwRop );
private const Int32 SRCCOPY = 0xCC0020;
public void SaveImage( string filename ) { using ( Graphics g1 = CreateGraphics() ) { Image image = new Bitmap( ClientRectangle.Width, ClientRectangle.Height, g1 ); using ( Graphics g2 = Graphics.FromImage( image ) ) { IntPtr dc1 = g1.GetHdc(); IntPtr dc2 = g2.GetHdc(); BitBlt( dc2, 0, 0, ClientRectangle.Width, ClientRectangle.Height, dc1, 0, 0, SRCCOPY ); g2.ReleaseHdc( dc2 ); g1.ReleaseHdc( dc1 ); } image.Save( filename, ImageFormat.Bmp ); } } }
Simon Murrell, and Lion Shi, # No product version has been specified for this FAQ item. Please report status updates here. How do I access a TextBox on one Form from another Form? One way to do this is to make the TextBox either a public property or a public field. Then you will be able to access it through the instance of its parent form. So, if TextBox1 is a public member of FormA and myFormA is an instance of FormA, then you can use code such as string strValue = myFormA.TextBox1.Text;
anywhere myFormA is known. Here is a VB project illustrating this technique. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I show a form without making it active? Normally when you make a Form visible by setting the Visible property to true, it will show the form and set the focus too. In some cases however, you do not want it to take focus until the user clicks on it. To get this behavior, do the following utility code: When you want to show a form without activating it: UtilFuncs.SetVisibleNoActivate( myForm, true ); // true to show.
When you want to hide it: UtilFuncs.SetVisibleNoActivate( myForm, false ); // false to hide.
public class UtilFuncs { [ DllImport( "user32.dll" ) ] extern public static bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags ); public const int HWND_TOPMOST = -1; // 0xffff public const int SWP_NOSIZE = 1; // 0x0001 public const int SWP_NOMOVE = 2; // 0x0002 public const int SWP_NOACTIVATE = 16; // 0x0010 public const int SWP_SHOWWINDOW = 64; // 0x0040 public static void ShowWindowTopMost( IntPtr handle ) { SetWindowPos( handle, (IntPtr) HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_SHOWWINDOW ); } public static void SetVisibleNoActivate( Control control, bool visible ) { if ( visible ) ShowWindowTopMost( control.Handle ); control.Visible = visible; } }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I catch an exception that occurs anywhere in a Windows Forms application? You can handle the Application.ThreadException event from the System.Windows.Forms namespace. using System.Threading;
[STAThread] public static void Main() { Application.ThreadException += new ThreadExceptionEventHandler( UnhandledExceptionCatcher ); Application.Run( new Form1() ); }
private static void UnhandledExceptionCatcher(object sender, ThreadExceptionEventArgs e) { Console.WriteLine( "Caught an unhandled exception" ); }
See Application.ThreadException in the .NET Framework Class Library for a more detailed sample in both VB and C#. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I add items to the system menu of a Form? To do this, you can use use iterop to access the GetSystemMenu and AppendMenu Win32 APIs. You also need to override the form's WndProc method to catch and act on the menu message. This idea was posted in the Microsoft newsgroups by Lion Shi. Here are some sample projects. George Shepherd, Syncfusion, and Lion Shi, # No product version has been specified for this FAQ item. Please report status updates here. How do I programmatically set a Form's icon from a bitmap? You could do so as shown in the code below : Form form1 = new Form(); Bitmap bmp = imageList1.Images[index] as Bitmap; form1.Icon = Icon.FromHandle(bmp.GetHicon());
Please refer to the sample attached here that illustrates this. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I set the company name that is returned by System.Windows.Forms.Application.CompanyName? This is an assembly attribute. The Visual Studio development environment sets it in the AssemblyInfo.cs (or .vb) file. If you open that file, you will see a block of assembly attributes that you can set, including company and version numbers. [assembly: AssemblyCompany( "Syncfusion, Inc." )]
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I display a status dialog in a background thread during a long operation and allow the user to cancel? You can do this by starting a new thread and executing Application.Run for the status dialog form when the background thread starts running. To communicate changes in percentage use BeginInvoke to executes a specific delegate asynchronously on the thread that the form was created on. Download the ProgressThread progressthread.zip sample for a complete implementation of a BackgroundThreadStatusDialog class that shows a status dialog in a separate thread. In order to use BackgroundThreadStatusDialog from your code you have to update the progess inside your loop and check the IsCanceled state to detect if the user pressed the Cancel button. private void button1_Click(object sender, System.EventArgs e) { BackgroundThreadStatusDialog statusDialog = new BackgroundThreadStatusDialog(); try { for (int n = 0; n < 1000; n++) { statusDialog.Percent = n/10; int ticks = System.Environment.TickCount; while (System.Environment.TickCount - ticks < 10) ; if (statusDialog.IsCanceled) return; } statusDialog.Close(); MessageBox.Show(statusDialog.IsCanceled ? "Canceled" : "Success"); } finally { statusDialog.Close(); } }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I easily manage whether controls on a form are read-only or not? One way is to place all the controls into a single GroupBox and then use the GroupBox.Enabled property to manage whether the controls are editable or not. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I detect if the user clicks into another window from a modal dialog? Use the Form.Deactivate event: Deactivate += new EventHandle( OnDeactivate ); // ...
private void OnDeactivate( object s, EventArgs e ) { Close(); }
Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I get an HWND for a form or control? See the Control.Handle property which returns the HWND. Be careful if you pass this handle to some Win32 API as Windows Forms controls do their own handle management so they may recreate the handle which would leave this HWND dangling. Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I prevent a form from being shown in the taskbar? You need to set the form's ShowInTaskbar property to False to prevent it from being displayed in the Windows taskbar. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I ensure that a form will always be on the desktop? To set or control the location of the form using desktop coordinates, you can use the SetDeskTopLocation property. You can do this by setting the child form's TopMost to False and setting its Owner property to the Main Form. this.SetDesktopLocation( 1, 1 );
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a non-modal top level form that always stays on top of all the app's windows? For example the Find dialog in Visual Studio. Make your main form the "Owner" of the form in question. Refer to Form.Owner in class reference for more information. findReplaceDialog.Owner = this; // where 'this' is the main form findReplaceDialog.TopLevel = false;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a form that is 'TopMost' for only my application, but not other applications? You can do this by setting the child form's TopMost to False and setting its Owner property to the Main Form. Form1 f = new Form1(); f.TopMost = false; f.Owner = this; f.Show();
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I share a common event handler across multiple controls? In VB6, I used control arrays to have a common handler handle events from several controls. How can I do this in Windows Forms? You can specify events from different controls be handled by a single method. When you define your handler, you can list several events that are to be handled by listing them in the Handles argument. This statement handles three different textbox's TextChanged event. Private Sub TextsChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged
In the TextsChanged handler, you may need to identify the particular control that fired the event. This sender parameter holds the control. You can use it with code such as: Dim eventTextBox as TextBox = sender
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Creating Forms and Controls How do I create an instance of a Form class from its name? You can use the System.Reflection.Assembly.CreateInstance method to create a form from its name. Below is a code snippet. The name in the textbox has to be the full name including its namespace. So if there is a class named Form2 in namespace MyCompanyName, then the textbox would contain MyCompanyName.Form2. This snippet also assumes that the class is defined in the current executing assembly. If not, you would have to create an instance of the assembly that contains the class instead of calling the static method GetExecutingAssembly. As noted on this board, using reflection in this manner might affect performance. You can download working samples (VB.NET, C#). try { Assembly assembly = Assembly.GetExecutingAssembly(); // if class is located in another DLL or EXE, // then use Assembly.LoadFrom("myDLL.DLL"); Form form = (Form) assembly.CreateInstance( textBox1.Text ); form.Show(); } catch ( Exception ex ) { MessageBox.Show( "Error creating: " + textBox1.Text ); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a form that starts out being not visible? Setting Form.Visible to false does not make my main form start up invisibly. How can I make my main form start up invisibly? This problem is discussed in an article in the .NET docs. Search for "Setting a Form to Be Invisible at Its Inception". The idea is to startup the application in a different module than your main form. Then the application and main form can have indiependent lifetimes. Sample code is given in the referenced article. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I ensure that no more than one instance of modeless dialog is created or open at a time? One way to do this is to maintain a list of opened modeless dialogs, and check this list before you open a new one to see if one is already present. If you open all these modeless dialog's from the same 'main' form, then you can use the OwnedForms property of that main form to maintain this list of opened dialogs. Below are some code snippets that suggest how you must go about this. Note that your dialog forms need to be able to turn off the ownership. This is done below by adding an Owner field to the dialog form. Sample code that either opens a new dialog or displays an already opened dialog: private void button1_Click( object sender, EventArgs e ) { foreach ( Form f in this.OwnedForms ) { if ( f is Form2 ) { f.Show(); f.Focus(); return; } }
//need a new one Form2 f2 = new Form2(); AddOwnedForm( f2 ); f2.Owner = this; f2.Show(); }
Form2 code: public class Form2 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; public Form Owner; // ...
private void Form2_Closing( object sender, CancelEventArgs e ) { Owner.RemoveOwnedForm( this ); } }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I add a control to a Window Form at runtime? There are three steps to adding a control at runtime. Create the control. Set control properties. Add the control to the Form's Controls collection. In general, if you need help on exactly what code you need to add, just look at the code generated by the Designer when you add the control at design time. You can usually use the same code at runtime. This code fragment creates a TextBox at runtime. [C#] TextBox tb = new TextBox(); // step 1
tb.Location = new Point( 10, 10 ); // step 2 tb.Size = new Size( 100, 20 ); tb.Text = "I was created at runtime";
this.Controls.Add( tb ); // step 3
[Visual Basic] Dim tb as TextBox = New TextBox() ' step 1
tb.Location = New Point(10, 10) ' step 2 tb.Size = New Size(100, 20) tb.Text = "I was created at runtime"
Me.Controls.Add(tb) ' step 3
Contributed from George Shepherd's Windows Forms FAQ, # This FAQ item is current to the .NET Framework 1.1 release. Please report status updates here. How do I dynamically load a control from an assembly (or DLL)? You use System.Reflection to dynamically load a control. This sample loads the SpecControls.ColorControl from SpecControls.dll. [C#] using System.Reflection;
Assembly assembly = Assembly.LoadFrom( "SpecControls.dll" ); Type t = assembly.GetType( "SpecControls.ColorControl" );
// create an instance and add it to the parent's controls Control c = (Control) Activator.CreateInstance( t ); parent.Controls.Add( c );
[Visual Basic] Imports System.Reflection
Dim assembly1 As Assembly = Assembly.LoadFrom("SpecControls.DLL") Dim t As Type = assembly1.GetType("SpecControls.ColorControl")
' create an instance and add it to the parent's controls Dim c As Control = CType(Activator.CreateInstance(t), Control) parent.Controls.Add(c)
Contributed from George Shepherd's Windows Forms FAQ, # This FAQ item is current to the .NET Framework 1.1 release. Please report status updates here. How do I programmatically add controls to a form and ensure they are displayed? The controls that I've try to add to my form at runtime don't show up. What's wrong? Make sure you implemented and executed code similar to the InitializeComponent method that VS adds to your Windows Forms project for controls added during design time. Recall that InitializeComponent() is called from your Forms constructor to create the controls, size, position and show the controls, and finally add the controls to the form's Controls collection. So, your code at runtime should also implement these same steps. In particular, don't forget the this.Controls.AddRange call that adds your new controls to the form's Controls collection. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Closing Forms and Exiting Applications How do I force a Windows Form application to exit? Your main form is an object of type System.Windows.Forms.Form. Use its Close method to exit the application. If you wish to Exit from a Form's constructor, this will not work. A workaround is to set a boolean flag that you can later check in the Form's Load method to call Close if required. Another way is to use the Application.Exit() method. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I determine if a form was closed from the system menu or a call to Form.Close? One way to do this is to override the form's WndProc method and check for WM_SYSCOMMAND and SC_CLOSE. Looking for WM_CLOSE in the override is not sufficient as WM_CLOSE is seen in both cases. A sample is available for download (C#, VB). public const int SC_CLOSE = 0xF060; public const int WM_SYSCOMMAND = 0x0112;
//_closeClick is a bool member of the form initially set false... // It can be tested in the Closing event to see how the closing came about. protected override void WndProc(ref System.Windows.Forms.Message m) { if ( m.Msg == WM_SYSCOMMAND && (int) m.WParam == SC_CLOSE ) this._closeClick = true; base.WndProc( ref m ); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I prevent a Form from closing when the user clicks on the close button? Handle the form's Closing event. private void Form1_Closing( object sender, CancelEventArgs e ) { if ( NotOkToClose() ) e.Cancel = true; //don't close }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I remove the Close button from a form's title bar? Set the property Form.ControlBox to false. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I display a confirmation dialog when the user closes the form? You can listen to the Form's Closing event, where you can display a MessageBox as show below: using System.ComponentModel;
private void Form1_Closing( object sender, CancelEventArgs e ) { string text = "Do you want to close the application?"; string caption = "Close Application"; if ( MessageBox.Show( text, caption, MessageBoxButtons.YesNo ) == DialogResult.No ) e.Cancel = true; }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Appearance How do I create a splash screen style form, i.e., with no border or titlebar? You can download a working project that uses this code. public void CreateMyBorderlessWindow() { FormBorderStyle = FormBorderStyle.None; MaximizeBox = false; MinimizeBox = false; StartPosition = FormStartPosition.CenterScreen; ControlBox = false; }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a form with resizing borders and no title bar? Set the form's Text and ControlBox properties. form1.Text = string.Empty; form1.ControlBox = false;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I make a form be transparent? The opacity property enables you to specify a level of transparency for the form and its controls. See the .NET documentation for Form.Opacity for differences between Opacity and TransparencyKey properties. Opacity only works with Windows 2000 and later. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I create non-rectangular forms? Check out this MSDN Library article Shaped Windows Forms and Controls in Visual Studio .NET by Seth Grossman of the Visual Studio Team. There are two ways to create non-rectangular windows. The first way is to change the Control.Region property, which, of course is inherited by Form. [C#] GraphicsPath gp = new GraphicsPath(); gp.AddEllipse( 0, 0, 100, 100 ); gp.AddRectangle( 50, 50, 100, 100); this.Region = new Region( gp );
[Visual Basic] Dim gp As New GraphicsPath() gp.AddEllipse(0, 0, 100, 100) gp.AddRectangle(50, 50, 100, 100) Me.Region = New [Region](gp)
The second way is to use the Form.TransparencyKey property. This tells the form not to paint any pixels that match the color of the TransparencyKey. So you can make your fancy skin bitmap, then set the TransparencyKey to be, say Color.Red, then all the pixels that are RGB(255,0,0) will be transparent. Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a form with no border? Use the Form.FormBorderStyle property to control a form's border. public void InitCustomForm() { // Adds a label to the form. Label label1 = new Label(); label1.Location = new System.Drawing.Point( 80, 80 ); label1.Name = "label1"; label1.Size = new System.Drawing.Size( 132, 80 ); label1.Text = "Start Position Information"; Controls.Add( label1 );
// Changes the border to Fixed3D. FormBorderStyle = FormBorderStyle.Fixed3D; // Displays the border information. label1.Text = "The border is " + FormBorderStyle; }
From the .NET Framework SDK documentation, # No product version has been specified for this FAQ item. Please report status updates here. How do I provide custom styling for Windows Forms, providing a similar function as CSS does for HTML? Here's what I use it in my code. 1. Set up a form for the user to select their style preferences. If this is not important to your app, go to step 2 and skip step 3. 2. Set up a Preference class. Imports System.Drawing
Public Class StylePreferences
Private Shared m_FrmBackColor As Color = Color.Tan Private Shared m_FrmTextColor As Color = Color.Black Private Shared m_FontFace As Font = New Font("Verdana", 10) Private Shared m_ButtonBackColor As Color = Color.Azure
' Additional fields...
Property FrmBackColor() As Color Get Return m_FrmBackColor End Get Set(ByVal Value As Color) m_FrmBackColor = Value End Set End Property
Property FrmTextColor() As Color ' ... End Property
Property FontFace() As Font ' ... End Property
Property ButtonBackColor() As Color ' ... End Property
' Additional properties... End Class
3. Create a Preference form for the user to control preferences, assign values from the form to an instance of the preference class: Private Sub SetStyle() Dim style As StylePreferences = New StylePreferences style.FrmBackColor = Me.BackColor style.FrmTextColor = Me.ForeColor style.FontFace = Me.Font
style.ButtonBackColor = Button1.BackColor ' Initialize addtional properties... End Sub
4. In each of your form loads, assign values from the preferences class: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As EventArgs) _ Handles MyBase.Load
Dim style As StylePreferences = New StylePreferences Me.BackColor = style.FrmBackColor Me.ForeColor = style.FrmTextColor Me.Font = style.FontFace
Button1.BackColor = style.ButtonBackColor Button2.BackColor = style.ButtonBackColor ' Initialize addtional properties...
End Sub
Notice that you do not have to assign every property on every control if you assign the form level ones first. This will act all the controls on the form, as is the case with the Font in this sample. Elizabeth Gee, 11 January 2005# No product version has been specified for this FAQ item. Please report status updates here. What are some best practices for drawing and painting in Window Forms? Check out Painting techniques using Windows Forms for the Microsoft .NET Framework by Fred Balsiger on WindowsForms.net. It is a good basic discussion of how to get the best performance from Windows Forms drawing. His hints include leveraging the power of the .NET Framework by using the proper controls and control styles as well as consolidating painting code in the OnPaint and OnPaintBackground methods. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I draw a line to replace the functionality of VB6's Line command? Try this code: Dim g as Graphics g = frmMain.CreateGraphics() g.DrawLine(Pens.Black, new Point(0,0), _ new Point(frmMain.ClientRectangle.Width), frmMain.ClientRectangle.Height) g.Dispose()
This should draw a line from the upper left to the bottom right corner of your application, but only if it's visible. If this code isn't in the paint event, when something obscures your application or it repaints, this line will not be redrawn. Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I suspend painting a form until all its controls are initialized? There is not currently a way to do this built into the framework, but WM_SETREDRAW will do what you're looking for. It can't be called recursively, so here's code for a property you can add to your form to handle it. A VB sample is also available. [ DllImport( "user32" ) ] private static extern bool SendMessage( IntPtr hWnd, int msg, int wParam, int lParam ); private const int WM_SETREDRAW = 0xB;
int paintFrozen;
private bool FreezePainting { get { return paintFrozen > 0; } set { if ( value && IsHandleCreated && Visible ) if ( 0 == paintFrozen++ ) SendMessage( Handle, WM_SETREDRAW, 0, 0 );
if ( !value ) { if ( paintFrozen == 0 ) return; if ( 0 == --paintFrozen ) { SendMessage( Handle, WM_SETREDRAW, 1, 0 ); Invalidate( true ); } } } }
Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I get EnableVisualStyles method to support XP styles in an application? Microsoft has confirmed that calling the Application.EnableVisualStyles method (in the System.Windows.Forms namespace) in the Main method resulting in some ImageList corruption is a bug. This workaround appears to solve the problem. public virtual void Main() { Application.EnableVisualStyles(); // Calling DoEvents after the above method call seems to fix this issue Application.DoEvents(); Application.Run( new Form1() ); }
George Shepherd, Syncfusion, and Martin Robins, # No product version has been specified for this FAQ item. Please report status updates here. How do I use XP Themes with Windows Forms using the .NET Framework 1.1? The .manifest file is not required if you are using .NET FrameWork 1.1. You can now use the application's EnableVisualStyles() method which should called before creating any controls. You also need to ensure that the FlatStyle property of the control is changed to System/b> instead of the default value of Standard. static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I use XP Themes with Windows Forms using the .NET FrameWork 1.0? Follow these steps to introduce Windows XP visual styles into your Windows application. 1. Create a new Windows Application and add some controls to the default form. 2. For every control you place on the form that has a FlatStyle property, set the property to System. 3. Compile your application. 4. Build a manifest file in the application directory. NOTE: This manifest file must be located in the same directory as the executable. Open Notepad and place the code shown below in the file. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Layout What control should I use to create separator lines between controls on a form? Use the Label control with its BorderStyle set to Fixed3D and height set to 2. Contributed from George Shepherd's Windows Forms FAQ, # This FAQ item is current to the .NET Framework 1.1 release. Please report status updates here. How do I postpone the resizing controls until the form's resizing is complete? I have a form with several controls on it. As I size the form, the controls are being resized continuously. Is it possible to postpone changing the controls position until the resizing is complete? The idea is to do the painting on Idle. This means you simple invalidate when being sized and then do your full paint when the size completes. Here is the code that you would add to your form. bool idleHooked = false; protected override void OnResize(EventArgs e) { if (!idleHooked) { Application.Idle += new EventHandler(OnIdle); } } private void OnIdle(object s, EventArgs e) { Invalidate(); PerformLayout(); if (idleHooked) { Application.Idle -= new EventHandler(OnIdle); } }
George Shepherd, Syncfusion, and Shawn Burke, Microsoft, # No product version has been specified for this FAQ item. Please report status updates here. How do I create a custom layout engine? Chris Anderson discusses how to implement a custom layout engine and gives sample code in the article Providing Custom Layout Engines for Windows Forms (also available here). Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I programmatically set the initial position of a Form so that it is displayed properly on invocation through ShowDialog()? In addition to setting the Location property of the form, make sure you also set the StartPosition property of the form to FormStartPosition.Manual. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Position, Size and Movement How do I programmatically maximize or minimize a form? Set the System.Windows.Forms.Form.WindowState property to FormWindowState.Maximized or FormWindowState.Minimized. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I make a form cover the whole screen including the TaskBar? The following code snippet demonstrates how you can make your form cover the whole screen including the Windows Taskbar. // Prevent form from being resized. FormBorderStyle = FormBorderStyle.FixedSingle;
// Get the screen bounds Rectangle formrect = Screen.GetBounds( this );
// Set the form's location and size Location = formrect.Location; Size = formrect.Size;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I position a form at the bottom right of the screen, above the system tray, when it opens up the first time? Do as follows in your Form's constructor after setting the StartPosition to Manual: SetBounds( Screen.GetWorkingArea( this ).Width - Width, Screen.GetWorkingArea( this ).Height - Height, Width, Height );
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I prevent a user from moving a form? The following code snippet (posted in the Windows Forms FAQ forums) shows how you can prevent a user from moving a form at run time: protected override void WndProc( ref Message m ) { const int WM_NCLBUTTONDOWN = 161; const int WM_SYSCOMMAND = 274; const int HTCAPTION = 2; const int SC_MOVE = 61456;
if ( (m.Msg == WM_SYSCOMMAND) && (m.WParam.ToInt32() == SC_MOVE) ) return; if ( (m.Msg == WM_NCLBUTTONDOWN) && (m.WParam.ToInt32() == HTCAPTION) ) return;
base.WndProc( ref m ); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I restrict or control the size of a form? You can restrict the size of a form by setting it's MaximumSize and MinimumSize properties. This will help you control the maximum and minimum size the form can be resized to. Also note that WindowState property of the form plays a part in how the form can be resized. // Minimum width = 300, Minimum height= 300 this.MinimumSize = new Size(300, 300); //Maximum width = 800, Maximum height= unlimited this.MaximumSize = new Size(800, int.MaxValue);
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I prevent users from resizing a form? You can prevent users from resizing a form by setting the FormBorderStyle to FixedDialog and setting the MaximizeBox property to false. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I automatically resize a Form when the screen resolution changes between design-time and runtime? The framework automatically resizes the form if the current Font size during runtime is different from the font size in design-time. It however doesn't auto size when the resolution changes. But it should be easy for you to accomplish. You could derive a custom Form, provide a "ScreenResolutionBase" property that could return the current screen resolution (Screen.PrimarScreen.Bounds will give you this). This value will get serialized in code during design time. Then during runtime in the Form's OnLoad you could check for the current screen resolution and resize the Form appropriately. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I center a form? Set the Form's StartPosition property to CenterScreen. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I support moving a borderless form? This code snippet shows how you can move a borderless form. private const int WM_NCLBUTTONDOWN = 0xA1; private const int HTCAPTION = 0x2;
[ DllImport( "user32.dll" ) ] public static extern bool ReleaseCapture();
[ DllImport( "user32.dll" ) ] public static extern int SendMessage( IntPtr hWnd, int Msg, int wParam, int lParam );
private void Form1_MouseDown( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Left ) { ReleaseCapture(); SendMessage( Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0 ); } }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I resize a borderless form with a rubber-band effect? See the Rubber Band Effect in a Form sample from Simon Bond at C# Corner that implements this sizing technique. Be sure to read the article Debugging "Rubber Band Effect", where Zhanbo Sun suggests a modification that handles a problem he spotted with the original code. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Cursor How do I change the cursor for a control? button1.Cursor = new Cursor( @"C:\winnt\cursors\hnodrop.cur" );
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I convert a Cursor class to a cursor (.cur) file? protected void WriteCursorToFile( Cursor cursor, string fileName ) { TypeConverter converter = TypeDescriptor.GetConverter( typeof( Cursor ) ); byte[] blob = converter.ConvertTo( cursor, typeof( byte[] ) ) as byte[]; if ( blob == null ) { MessageBox.Show( "Unable to convert Cursor to byte[]" ); return; } FileStream fileStream = new FileStream( fileName, FileMode.Create ); fileStream.Write( blob, 0, blob.Length ); fileStream.Flush(); fileStream.Close(); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I load and display a cursor from a resource manifest? System.IO.Stream stream = null; try { string curName = "WindowsApplication1.Cursor1.cur"; stream = GetType().Assembly.GetManifestResourceStream(curName); this.Cursor = new Cursor( stream ); } catch ( Exception ex ) { MessageBox.Show(ex.Message.ToString()); } finally { if ( stream != null ) stream.Close(); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. When I set the current cursor to the wait cursor, why does it revert before I want it to? I set the wait cursor using Cursor.Current = Cursors.WaitCursor;. Why does does it disappear before I want it to? Setting the Current property changes the cursor and stops the processing of mouse events. Setting the cursor back to Cursors.Default restarts the mouse event processing and displays the proper cursor for each control. If a DoEvents is called before you reset the cursor back to the default, this will also start up the mouse event processing and you will lose the particular cursor you set. So, if your WaitCursor is disappearring, one explanation might be that DoEvents is getting called. Here is some code that sets a WaitCursor. Cursor oldCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; try { // Do your processing that takes time, e.g., wait for 2 seconds DateTime dt = DateTime.Now.AddSeconds(2); while ( dt > DateTime.Now ) {} } finally { Cursor.Current = oldCursor; }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Keyboard How do I send keystrokes to an application? What is the replacement for VB6's SendKeys command? Use the Send method from the SendKeys class found in the System.Windows.Forms namespace. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I process keyboard messages on an application-wide basis? You can implement the IMessageFilter interface in your main form. This amounts to adding an override for PreFilterMessage, and looking for the particular message you need to catch. Here are code snippets that catch an escape key on a keydown. You can download a sample project(C#, VB). In the sample, there are two forms, with several controls. You'll notice that no matter what form or control has input focus, the escape key is caught in the PreFilterMessage override. [C#] public class MyMainForm : System.Windows.Forms.Form, IMessageFilter { const int WM_KEYDOWN = 0x100; const int WM_KEYUP = 0x101; public bool PreFilterMessage(ref Message m) { Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode; if(m.Msg == WM_KEYDOWN&& keyCode == Keys.Escape) { Console.WriteLine("Ignoring Escape..."); return true; } return false; } .... private void MyMainForm_Load(object sender, System.EventArgs e) { Application.AddMessageFilter(this); } }
[Visual Basic] Public Class MyMainForm Inherits System.Windows.Forms.Form Implements IMessageFilter Private WM_KEYDOWN As Integer = &H100 Private WM_KEYUP As Integer = &H101 Public Function PreFilterMessage(ByRef m As Message) As Boolean Dim keyCode As Keys = CType(CInt(m.WParam), Keys) And Keys.KeyCode If m.Msg = WM_KEYDOWN And keyCode = Keys.Escape Then Console.WriteLine("Ignoring Escape...") Return True End If Return False End Function 'PreFilterMessage .... Private Sub MyMainForm_Load(sender As Object, e As System.EventArgs) Application.AddMessageFilter(Me) End Sub 'MyMainForm_Load End Class 'MyMainForm
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I process certain keys at the Form level, irrespective of which control has the focus? When the Form.KeyPreview property is set to true, the Form's KeyPress, KeyDown and KeyUp events will be fired even before the Control with the focus' corresponding events. You may choose to forward these message to the Control after processing them in the Form's event handlers (this happens by default) or set the e.Handled property to true (in the event argument) to prevent the message from being sent to the Control with focus. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
MDI: Multiple Document Interface How do I create an MDI application using the .NET Framework? This is one of the QuickStart Samples that ships with Visual Studion .NET. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I change the background of an MDI Client container? The default behavior is to make the client container use the Control color from the Control panel. You can change this behavior by making the MDI Client container use the form's BackColor and Image. To do this, after the call to InitializeComponents(), add the code below. You can also download a working MDI Client project that has this code in it. //set back color foreach ( Control c in Controls ) { if ( c is MdiClient ) { c.BackColor = BackColor; c.BackgroundImage = BackgroundImage; } }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I make a child Form fill the entire MDI client without being maximized? Here is how it can be done. This takes into account all docked controls (including menus) in the mdi parent form. [C#] private void FillActiveChildFormToClient() { Rectangle mdiClientArea = Rectangle.Empty; foreach ( Control c in Controls ) if (c is MdiClient ) mdiClientArea = c.ClientRectangle;
ActiveMdiChild.Bounds = mdiClientArea; }
[Visual Basic] Private Sub FillActiveChildFormToClient() Dim mdiClientArea As Rectangle = Rectangle.Empty Dim c As Control For Each c In Controls If TypeOf c Is MdiClient Then mdiClientArea = c.ClientRectangle End If Next ActiveMdiChild.Bounds = mdiClientArea End Sub
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. Why is the Activated event not consistently fired when child forms are activated in an MDI application? In the .NET Framework 1.0, child forms do not get the Form.Activated event (only the parent MDI). To catch MDI children being activated, listen to the Enter/Leave events of that child Form or listen to the Form.MdiChildActivate event in the parent Form. In the .NET Framework 1.1 child Forms do get the Activated event. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I constrain the size of MDI child forms since MinimumSize and MaximumSize properties don't seem to work? It appears that this behavior is a bug that will be corrected in a future .NET release. You can control the size of your child form by adding a Layout event handler for it. Here is a code snippet that imposes the minimum size that you set in its properties. You can also handle it by overriding the form's WndProc method as explained in FIX: MinimumSize and MaximumSize Properties Are Not Obeyed When Window Is an MDI Child (Article ID: 327824) [C#] private void Document_Layout( object sender, LayoutEventArgs e ) { if ( Bounds.Width < MinimumSize.Width ) Size = new Size( MinimumSize.Width, Size.Height ); if ( Bounds.Height < MinimumSize.Height ) Size = new Size( Size.Width, MinimumSize.Height ); }
[Visual Basic] Private Sub Document_Layout(ByVal sender As System.Object, _ ByVal e As LayoutEventArgs) Handles MyBase.Layout If (Bounds.Width < MinimumSize.Width) Then Size = New Size(MinimumSize.Width, Size.Height) End If If (Bounds.Height < MinimumSize.Height) Then Size = New Size(Size.Width, MinimumSize.Height) End If End Sub
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I ensure that no more than one instance of a child form is created? Here are two ways you can do this. 1. Within the parent MDI form, use code such as this: // ChildForm is type being created or shown
ChildForm childForm = null; foreach ( Form f in MdiChildren ) if ( f is ChildForm ) { childForm = (ChildForm) f; break; }
if( childForm == null ) { childForm = new ChildForm(); childForm.MdiParent = this; }
childForm.Show(); childForm.Focus();
2. A second solution implements a singleton pattern on the child form. In the MDI Child form put this code in (where frmChildForm is the MDI child form you want to control) // Used for singleton pattern static ChildForm childForm; public static ChildForm GetInstance { if ( childForm == null ) childForm = new ChildForm(); return childForm; }
In the Parent MDI form use the following code to call the child MDI form ChildForm form = GetInstance(); form.MdiParent = this; form.Show(); form.BringToFront();
The first time this code is called, the static GetInstance method will create and return an instance of the child form. Every other time this code is called, the GetInstance method will return the existing instance of the child from, stored in the static field childForm. If the child form instance is ever destroyed, the next time you call GetInstance, a new instance will be created and then used for its lifetime. Also, if you need constructors or even overloaded constructors for your MDI Child Form, just add the needed parameters to the GetInstance function and pass them along to the class constructor. George Shepherd, Syncfusion, and John Conwell, # No product version has been specified for this FAQ item. Please report status updates here. How do I perform custom processing when an MDI child form is added to or removed from the MDIContainer form? MDIContainer forms have an MDIClient child window and it is to this MDIClient window that MDI child forms are parented. The MDIClient's ControlAdded/ControlRemoved events will be fired whenever a child form is added or removed. You can subscribe to these events and add the required processing code from within the handlers. From within the MDIContainer form, subscribe to the MDIClient's ControlAdded/ControlRemoved events foreach( Control ctrl in Controls ) if ( ctrl.GetType() == typeof( MdiClient ) ) { ctrl.ControlAdded += new ControlEventHandler( MDIClient_ControlAdded ); ctrl.ControlRemoved += new ControlEventHandler( MDIClient_ControlRemoved ); break; }
protected void MDIClient_ControlAdded( object sender, ControlEventArgs e ) { Form childform = e.Control as Form; Trace.WriteLine( String.Concat( childform.Text, " - MDI child form was added." ) ); }
protected void MDIClient_ControlRemoved( object sender, ControlEventArgs e ) { Trace.WriteLine( String.Concat( e.Control.Text, " - MDI child form was removed." ) ); }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I perform custom painting (e.g., a logo) in an MDI container? You should not try listening to your MDI container Form's Paint event, instead listen to the Paint event of the MDIClient control that is a child of the mdi container form. This article provides you a detailed example: Painting in the MDI Client Area Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Common Dialogs (System.Windows.Forms.CommonDialog) How do I use the OpenFileDialog? using System.Text; using System.IO;
private string ChooseTextFile( string initialDirectory ) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Open text file"; dlg.InitialDirectory = initialDirectory; dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; return ( dlg.ShowDialog() == DialogResult.OK ) ? dlg.FileName : null; }
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I specify the path for the FolderBrowser instance when it opens the first time? In the .NET Framework 1.1 there is a SelectedPath property that will let you do this. Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I implement a Folder Browser class? Below is a technique that uses FolderNameEditor and FolderBrowser classes to implement a solution. You can also use iterop to get a solution. Both the FolderNameEditor and FolderBrowser classes used in this solution are described in the Docs as "This type supports the .NET Framework infrastructure and is not intended to be used directly from your code." // add a reference to System.Design.DLL using System.Windows.Forms.Design;
public class DirectoryBrowser : FolderNameEditor { private string description = "Choose Directory"; private string returnPath = string.Empty; FolderBrowser browser = new FolderBrowser(); public string Description { get { return description; } set { description = value; } }
public string ReturnPath { get { return returnPath; } } public DialogResult ShowDialog() { browser.Description = description; browser.StartLocation = FolderBrowserFolder.MyComputer; DialogResult result = browser.ShowDialog(); returnPath = ( result == DialogResult.OK ) ? browser.DirectoryPath : string.Empty; return result; } }
Ryan Farley, # No product version has been specified for this FAQ item. Please report status updates here. How do I use the FontDialog class to set a control's font? It is straightforward. Create an instance of the class and call its ShowDialog method. FontDialog fontDialog1 = new FontDialog(); if ( fontDialog1.ShowDialog() != DialogResult.Cancel ) textBox1.Font = fontDialog1.Font ;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here. How do I use the ColorDialog to pick a color? It is straightforward. Create an instance of the class and call its ShowDialog method. ColorDialog colorDialog1 = new ColorDialog(); if ( colorDialog1.ShowDialog() != DialogResult.Cancel ) textBox1.ForeColor = colorDialog1.Color;
Contributed from George Shepherd's Windows Forms FAQ, # No product version has been specified for this FAQ item. Please report status updates here.
Resources |