Here are some frequently asked questions about Windows Forms and their answers.
Browse by Tags
All Tags » Forms (RSS)
-
|
The section lists out common performance problems and suggested solutions. Changing the UI in OnLoad Problem : Changing properties such as Bounds, Size, Location, Visible and Text/Image/etc for AutoSized controls InitializeComponent and/or Suspend/ResumeLayout...
|
-
|
Text clipping via Localization - When a localizer changes the text increases the size of the control by changing the text – will anything be clipped? Problem: Changing the text in another language can cause elements of the UI to overlap. Solution: There...
|
-
|
Each text field can grow by 30% without clipping The dialog can respond to High Contrast without clipping The dialog can respond to font changes without clipping The dialog can respond to DPI changes without clipping The dialog can be switched to RightToLeft...
|
-
|
This lists contains all the "reasons" for layout we pass to the LayoutEventArgs. Usually the strings correspond to the properties. Alignment ColumnStyles ImageIndex Orientation ShowImageMargin Anchor Controls ImageScaling PreferredSize ShowCheckMargin...
|
-
|
SuspendLayout and ResumeLayout only prevent OnLayout from being called. Additionally they only prevent OnLayout from being called for that particular control. So if you have a Form with a Panel in it, and call SuspendLayout on the Form, the Panel's...
|
-
|
In the UI that you believe to be laying out the most, either override OnLayout or sync the Layout event. In the event use Debug WriteLines to write both the current size of the control and the call stack of how we got here. You can also print out the...
|
-
|
Padding is the internal space you can add to your control/item Margin is the external space you can add to separate controls/items. Depending on the implementation of GetPreferredSize for a control, changing the Padding property can inflate the control...
|
-
|
The simple answer is this is not possible. When you set an anchor, the dock style clears. And vise versa if you set the dock style. Under the covers, we use the same bit fields to represent dock and anchor, so it is not possible to get into a conflicting...
|
-
|
Dock and anchor concepts apply to the default layout used for Forms. Simply put, anchor maintains the distance between the edge of the control and the corresponding edge of the container in which it is anchored. By default, controls are anchored top left...
|
-
|
The best way to ensure a particular height or width for a control is to override the control's SetBoundsCore method. This sample shows a Button which has a fixed height and width. The same technique can be used to set upper- and lower-bounds on sizes...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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
|
-
|
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 (*...
|
-
|
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...
|
-
|
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...
|
-
|
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;...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
This is one of the QuickStart Samples that ships with Visual Studion .NET. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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...
|
-
|
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"...
|
-
|
Set the Form's StartPosition property to CenterScreen . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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...
|
-
|
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
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
Set the System.Windows.Forms.Form.WindowState property to FormWindowState.Maximized or FormWindowState.Minimized. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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
|
-
|
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
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
Set the form's Text and ControlBox properties. form1.Text = string.Empty; form1.ControlBox = false; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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...
|
-
|
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?";...
|
-
|
Set the property Form.ControlBox to false. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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"...
|
-
|
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...
|
-
|
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
|
-
|
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...
|
-
|
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...
|
-
|
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
|
-
|
Use the Form.Deactivate event: Deactivate += new EventHandle( OnDeactivate ); // ... private void OnDeactivate( object s, EventArgs e ) { Close(); } Shawn Burke, Microsoft
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
Check out Working with Multiple Forms in Visual Basic .NET: Upgrading to .NET by Duncan Mackenzie in the MSDN Library. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
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
|
-
|
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
|
-
|
I would like to use the Region property to create a form with hidden non-client areas (not exactly a rectangle), but I can't determine the client area rectangle position in non-client coordinates. The code I usually use to get this offset is: Point...
|
-
|
I have an MDI application, but when I switch between MDIChild windows, there are always flickers. The newly active MDIChild window flashes its borders which is disturbing. If it matters, I always use Maximized MDI Child windows. How can I eliminate this...
|
-
|
Here is a simple, complete source for creating MDI child windows. To build, reference System, System.Drawing, and System.Windows.Forms. using System; using System.Windows.Forms; namespace Application1 { class Program { static void Main( string[] args...
|