Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Everything / desktop / WinForms

WinForms

WinForms

Great Reads

by Code Artist
(AGauge) WinForms Gauge control
by carlos@takeapps
A basic .NET file browser fully based on the framework
by Fred Wang
An article on resolving the issue of unintentional web form resubmission.
by SprinterDave
A native .NET library and application to view the PNGs embedded in a MNG

Latest Articles

by Code Artist
(AGauge) WinForms Gauge control
by carlos@takeapps
A basic .NET file browser fully based on the framework
by Fred Wang
An article on resolving the issue of unintentional web form resubmission.
by SprinterDave
A native .NET library and application to view the PNGs embedded in a MNG

All Articles

Sort by Score

WinForms 

by The Zakies
Part 3 of a tutorial to show a graphics program using C# using GDI and SVG drag and drop and delete objects
by The Zakies
we will build an outline line around the drawn lines so we would test the mouse click on this outline to know which line is selected. and we would in the coming update build a select function inside the move tool
by The Zakies
in this tut we will create a technique to enable the user to control points within a drawn line, by drawing circles around points of the line , when the user clicks a circle he would control the corresponding point.
by The Zakies
we would create Hand_tool to pan through the drawing form, and we would use a custom cursor of open and closed hands
by The Zakies
we will continue the functionality of the hand tool with having a navigator panel which works as a map, we will also have a red rectangle which tells the user where he is actually viewing inside the whole form, also it can be moved to pan the form
by The Zakies
[tut4] how to draw lines & to draw different types on end shapes like rectangle and circle using C#
by The Zakies
Learn how to implement a tecnique of a parent form that createes and controls other forms , through the tecnique of using the tab control, also learn how to implement a menu for the tools, and how to add cutom cursor for each tool
by agent154
A method to move rows within a DataTable
by johannesnestler
Nice solution agent154, I'd just suggest to implement it as extension methods for data row: (and I don't liked your "error reporting" with the '0' Value - because '0' could be a valid index). But I have to say, even if you don't have a database behind the datatable you can use sorting (LINQ,...
by bobishkindaguy
A simple entry box for various numbers, especially phone numbers.
by Tony Zackin
A very simple yet customizable pop-up message box which auto-closes after a specified number of milliseconds.
by Vladyslav Chernysh
The goal of this tip is to share knowledge and experience on ActiveX usage in .NET applications (back-end & front-end).
by OriginalGriff
The Visual Studio Property pane is a control, which can be used in WinForms like any other, and it provides a simple, easy to use property editor for your classes. However, it is not obvious how to get it to open a browse dialog for a file path property.
by Santosh Kokatnur
Adding Checkbox to a List View Column Header in C# WindowsForm application
by PIEBALDconsult
This is an alternative for "Adding Functionality To .NET Controls"
by OriginalGriff
How to add images to a Winforms Project so they are accessible as resources
by Armando de la Torre
Use an error log control to validate forms.
by Code Artist
DataGridViewEx is an extension class created to extend WinForms DataGridView control with advance editing features.
by Alexandros Pappas
Display of a context menu when pressing the Apps key in a DevExpress GridControl
by #realJSOP
How to automatically display a Winforms menu when the mouse is hovered over an item
by Igor Pashchuk, MBA
This is an alternative for "C# Pivot Table"
by adriancs
A tool to backup & restore all MySQL databases in one click
by sreeyush sudhakaran
VB.NET code for Base64 Encoding and Decoding of Image files
by TarikHuber
Use STT (SQL Table Toolkit) to bind WinForm Controls to a DataGridview and to define ComboBox data sources
by manchanx
Tidy, generic solution to bind Enums (with or without a DescriptionAttribute) to a ComboBox or other Controls
by Ozesh Thapa
Choose your datasource and generate classes
by pgmr_64804
C# Gantt Chart For Winforms
by _Matt_Wilkinson_
How to centralise a Form when using multiple screens
by Harvey Saayman
Below is an example of changing the individual row colors based on one of the DataGridView's columns.While this is not hard to do, the property isn't always where you think it should be, its hidden within the rows DefaultCellStyle property.Here's the example:foreach (DataGridViewRow...
by dwilliss
Another way to do something like this is to handle the RowPrePaint event and change the background there. The advantage to doing it this way is that if you have thousands of rows, you don't have to set it for every row at the beginning, which could take a few seconds. This way only sets it for...
by Lakhan Aanjana
If cell color is depend on criteriaif (ca.con.State == ConnectionState.Closed) { ca.con.Open(); } string qry = "select * From productmaster "; SqlDataAdapter da = new SqlDataAdapter(qry, ca.con); DataSet ds1 =...
by Manfred Rudolf Bihy
Using SendMessage and the PARAFORMAT structure, one can easily change the line spacing in a RichTextBox control
by TarikHuber
Easy library for checking VAT Numbers of European Companies. Only usable with an German VAT for non German VAT!!!
by Tecfield
Collapsible ListView
by B.O.B.
A simple extension to add an item that has a data source bound to combobox.items
by Serge Weinstock
A ComboBox whose suggestion list is based on loose character search
by Bikash Karmokar
Connecting Windows Form Application With ADO.NET in C#
by Frans Jan
This article shows how to save a Windows Form to a PDF file.
by Altaf Ansari
Converting XML Data into DataTable and Exporting DataTable into Excel File
by #realJSOP
Determine the number of unique colors in an image
by a_pess
I think we may check if the color is repeated or not, any how this another alternative but in VB.NetPublic Shared Function GetImageColorsCount(ByVal bitmap As Bitmap) As Integer Dim ColorList As New System.Collections.Generic.List(Of Integer) Dim clr As Integer For...
by Andrew Rissing
Just a few minor improvements to readability and such...The catch/throw isn't needed here, since you are just throwing it without doing anything in the catch block. A try/finally could have been used on its own.The try/finally isn't necessary because a using statement can achieve the same...
by Raje_
This is a simple demo of how to display the number of unique products from a DataGridView.
by Acharya Raja Sekhar
This tool helps a lot while capturing more number of snapshots. Example: Developers can use this tool to capture the UTR and save all snaps at the end to a Word document or save as individual images.
by Robert.Verpalen
DataGridViewGrouper: add grouping functionality to the .NET DataGridView
by Hassan Mokdad
This is a just a small tip to show a simple way of designing the user interface of Windows Forms for Desktops applications.
by BillWoodruff
An interesting change in behavior in VS 2010 Pro ?
by PIEBALDconsult
A binary search technique to determine which TabPage of a TabControl was clicked
by Lutosław
This method, although it doesn't use binary search, handles Multiline tab pages too.private static intGetTabIndexAt( System.Windows.Forms.TabControl tabControl, System.Drawing.Point point){ int result = -1; if (tabControl != null) { for (int i = 0;...
by Minh Danh Nguyen (ToughDev)
Depending on system preferences (in Control Panel/Sounds), the .NET WebBrowser control (just like Internet Explorer) may produce a click sound when changes are made programmatically to its DocumentText property, which is irritating to the user.There are two ways to avoid this:1. Use...
by emolina
Public Sub DisableSound() Dim keyValue As String keyValue = "%SystemRoot%\Media\" If Environment.OSVersion.Version.Major = 5 AndAlso Environment.OSVersion.Version.Minor > 0 Then keyValue += "Windows XP Start.wav" ElseIf Environment.OSVersion.Version.Major = 6 Then ...
by Member 8208766
To me the second method was problematic. After searching, I found an apparently equally good solution:webBrowser1.DocumentText = text;or in your case:webBrowser1.Document.Write("Hello, world!");from here:...
by pipiscrew
nah, try the light one ://at FormLOAD WB.Navigate("about:blank"); //at treeview event private void treeview_AfterSelect(object sender, TreeViewEventArgs e) { WB.Document.Body.InnerHtml = (dR["html"].ToString()); }
by #realJSOP
How to determine if your .Net app is running in the Visual Studio IDE
by Alan N
I use the following to insert pauses into console apps when they are vs hosted. In fact it's the final lines in my standard template for a console app to ensure that the console stays visible until I dismiss it.if (AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe",...
by intrueder
Extension method to make any WinForms control to be draggable at runtime
by Kristian Sixhøj
A code snippet which makes a borderless form draggable.
by Anshul R
The original snippet I made is in VB.NETProtected Overrides Sub WndProc(ByRef e As Message) MyBase.WndProc(e) If e.Msg = &H84 AndAlso e.Result = &H1 Then e.Result = &H2 End SubI used Reflector to translate it to C#protected override void WndProc(ref Message...
by Dima Popov
A slightly different solution.using System.Runtime.InteropServices;private const int WM_NCLBUTTONDOWN = 0xA1;private const int HTCAPTION = 0x2;[DllImport("User32.dll")]private static extern bool ReleaseCapture();[DllImport("User32.dll")]private static extern int...
by CharlieFoolsTheComputer
Constraining a form/dialog to a single monitor
by George Swan
Couldn't the class RegEdit be replaced by one simple method?private void SetKey(bool enableTaskManager) { using ( var mKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System")) {...
by ola halvorsen
When going from a multimonitor environment to a single monitor, windows get stuck on the other screens
by Pat FitzHenry
If you have a window off-screen, type alt-space, and the letter m. Left click the mouse. Then continually press the left mouse key while scrolling the mouse around until the window comes into view. Click anywhere on screen off the window to drop the window. This should work for programs where...
by MartinW1307
I have for years used the follow to fetch a window to a visible screen.1. Right click the window on the taskbar and select 'Move' (or use the keystrokes Alt-Space, M)2. Move the mouse a bit3. Press "left arrow"4. Move the mouse around - you will see the window outline ;) 5. left click...
by Luc Schenkeveld
Alternate 3Right click on the taskbar and use "Show Windows Side by Side"
by adriancs
A program/application for learning and writing HTML. Get instant visual effect side by side with your code as you type. Support HTML5, Javascript and CSS3 elements.
by Yvan Rodrigues
A few lines of code to make using the Windows Forms RichTextBox easier to use as a logging window.
by RakeshMeena
This extension can be used to update controls in a thread safe manner. This method requires a MethodInvoker delegate as input parameter. It just checks whether the control is on a different thread than the caller.
by SergeyT2
You can use Action instead of MethodInvoker as well. And ".Invoke" at the method is unnesessary.public static void ThreadSafeCall(this Control control, Action method){ if (control.InvokeRequired) { control.Invoke(method); } else { method(); ...
by charles922
Another way to implement Falling Blocks Game
by MayurDighe
This tip describes how to fill the PDF Form Template programmatically
by Vipul Bhatnagar
Create a multilingual application WPF
by Midi_Mick
An edit control for the masked input of GUIDs
by tumbledDown2earth
Hiding the form from alt-tab menu
by meaningoflights
Tried it in VB.NET Winforms app, but no luck. It's still shown in the alt-tab menu:Protected Overrides ReadOnly Property CreateParams As System.Windows.Forms.CreateParams Get Dim cp As CreateParams = MyBase.CreateParams cp.ExStyle = cp.ExStyle Or &H80 ...
by Gordon Kushner
Say you need capture an event for a control in a User Control and you are not permitted to change the control itself.You can hook into control events, even for private controls with this code://In a Windows Form//Get the private control cboSomePrivateControl from the user control's...
by Your Display Name Here
How to use WebBrowser, a form, and an MDI parent to open Excel files
by Sergi Ortiz Gomez
Quick tip for capture ENTER key in a Windows Form combobox
by Shahin Khorshidnia
Tag is a useful property, but when you need more than a Tag, what will you plan for it?
by youssef.obeid
This is to show you how to build a Dropdown button for Windows form
by basilke7007
How to create rounded edge button (rounded corner button) in Winforms
by CodeMajster
A detailed tutorial on how to embed multiple icons and color/animated cursors in VS2010 VB project assembly as native win32 resources.
by KazMaxLtd
This article describes how to hide or show TabControl tabs at runtime
by Bernhard Hiller
That's far too obscure.All you need to do is store a reference to the TabPage instance which was removed from the TabPages collection of the TabControl. You may use the form where the TabControl is placed for that purpose.You could also create your own TabControl which has an extra property...
by zheng shuo
This tip shows how to share data between two or more forms in a Winforms application.
by Alan N
Handling the Popup event raised by the System.Windows.Forms.ToolTip component would seem offer an ideal opportunity to alter the tooltip text to reflect an underlying change. Unfortunately the stack overflow caused by calling ToolTip.SetToolTip will soon put a stop to the attempt.The test...
by William Winner
First, why would you want to change the ToolTip text during the PopUp? Why not hook the MouseHover of the control that you want to change the ToolTip? Dynamically setting the ToolTip does not require hooking the PopUp event.How about: public partial class Form1 : Form { ...
by Armando de la Torre
How to activate a toolstrip button via a shortcut key
by KenBonny
This is nice for non standard buttons (like a CTRL + s), but OK and Cancel buttons have standard implementations in a Windows Form. Look for the properties AcceptButton and CancelButton of a Windows Form (not sure if this applies in ASP.NET or WPF, I need confirmation on that). There you can...
by The Zakies
Tutorial 2 (how to interactively add multiple shapes GDI using linked lists)
by Peer Adi
This is a liquid container control for displaying liquid level in container or tank.
by coffee_machine
A component to add localized strings to a Form's res'x.
by TheDotNetGeek
Code snippet to make a control's text font style to bold dynamically at runtime in a windows application
by Juan Davel
Managing Application Scoped Connection Strings
by harbor
Manual Scroll Panel in a Panel or UserControl with AutoScroll=false
by tumbledDown2earth
Trick for dragging the form while clicking on the client area
by Nitin Singh India
People wonder how do delegates work and the threading issues associated with multicast ones.
by #realJSOP
A useful technique that could be used for winform apps which require a login dialog
by #realJSOP
Allow any number of forms to be used as a main form with easy transitions between forms
by Johnny J.
A sample owner-drawn ComboBox
by selvaprakash.s
This tip will demonstrate how cookies are passed from one control to another control in C# .NET in authenticated webpage.
by Reader Man San
Plug-in Architecture To Work in WinForms MVC + WPF MVVM + ASP.NET MVC + Mobile (Xamarin MVC/PhoneGap MVC) + Win 10 Universal App MVC
by Thomas Daniels
A tip about how to set the position of a Windows Forms MessageBox in C#
by Keith Barrow
If you have a Winforms application that auto loads data, there is no doubt that you’ll have come across the problem of data loading at design time (i.e. when opening the code in the designer). At best, this slows the designer down, at worst it might crash VS and prevent the control from...
by Ron Beyer
If you are designing in a WinForms component, which is anything that derives from Control at some point (Forms, UserControls, panels, etc), then you can use the following code:if (this.Site.DesignMode) //Do stuff[edit]The above will throw an exception if Site is not set (in...
by tonyt
Either method is good for testing if you are in the designer, but another problem aside from preventing code execution, is preventing code from being jitted in the Designer. For example, you may reference assemblies or components that are dependent on native code, which cannot be loaded into any...
by shelby67
Dialog for product key entry
by Graham Wilson
A method of ensuring that SplitterContainer controls with fixed panels are properly resized when AutoScaleMode is ScaleMode.DPI
by Simon Bridge
Full code listing for a very simple but effective Colour-Combo (Color for those in America)
by wmjordan
Rendering text with OpenType fonts by P/Invoking GDI API in WinForm applications.
by Wendelius
The tip shows one way to resolve if a user control is in design mode.
by Midi_Mick
This is an alternative for "Resolve DesignMode for a user control"
by intrueder
Extension method to make it easy to retrieve all nodes of a TreeView control.
by Richard Deeming
You can make this slightly more reusable by targeting the IEnumerable interface and providing a function to return the children of each item:public static class EnumerableExtensions{ private static IEnumerable DescendantsAndSelfIterator( IEnumerable source, ...
by leppie
Here is yet another alternative (originally from http://xacc.wordpress.com/2009/03/05/tree-traversal-extension-methods/[^]):public static class TreeExtensions{ public static IEnumerable TraverseDepthFirst( this T t, Func valueselect, Func<T,...
by springy76
By using a LinkedList, you can even mimic true recursive behavior without using recursive calls; the order will be "0,3,9,10,4,1,5,11,12,2,6,7,8", then:public static IEnumerable GetRecursive(this IEnumerable source, Func> subSelector){ var...
by charles henington
Run Only One Copy Of Application
by RaviRanjanKr
Yet another way to this is as follows: using System;using System.Collections.Generic;using System.Windows.Forms;using System.Threading;namespace OnlyOneInstance{ static class Program { [STAThread] static void Main() { bool...
by Neil A. Harding
I actually use code like this, which allows me to detect a existing instance and to call the original instance with the command line (I expand any filenames present so that it can access the filenames even if the original path is different).string processName =...
by FDW
Maybe this is helpful, it tries to switch to the first running instance:namespace UltraSimple.Win{ static class Program { [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [STAThread] ...
by tlhIn`toq
Just because we like C# doesn't mean we can't borrow from other .NET languages. I've always had good luck and less complication using VB's single instance methodology in my C# applications. This code would go in your program.cs file:/// /// We inherit from...
by KevinPorter
How about using a Mutex? This should also work for Terminal Services sessions. Use in Program.csstatic Mutex mut;try{ bool isOwned = false; mut = new Mutex(true, Application.ProductName + " MUTEX: {53A4988C-F91F-4054-9076-220AC5EC03F3}", out isOwned); if (!isOwned)...
by Henry Minute
Never code whilst holding scissors. That is not what is meantby the 'cut' in cut and paste.
by asiwel
Simple C# methods for saving snapshot images of a WinForm to the desktop
by Vano Maisuradze
Select only one node in Treeview
by Sagotharan Jagadeeswaran
Thanks, I am just changing False to True, And I got Automatically Check TreeView Child Nodes When Parent Is Checked.private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Node.Checked) { ...
by zidane168
This topic focuses on what is the difference between SendMessage and PostMessage and how to use them?
by Sreedeep.S
Serial Communication with the .NET Framework in Winforms
by cwfong
Make these controls read-only on WinForm
by avigodse
This article is created for setting the tab focus on the controls, where the error-provider has error text.
by Akos Orban
Set Owner of a WPF Window to a Form
by R.Tarik
Print you PDF silently using C#
by Midi_Mick
The simplest solution for adding a custom collection of custom objects to the designer
by Nejimon CR
Make irregular splash screens without writing a single line of code!
by Manish K. Agarwal
Single Instance Form in a MDI application
by Ctznkane
Assuming you only want a single instance of a form type, I'd suggest you add a Dictionary(Of Type, Form). ShowOrActiveForm would have a single parameter of Type and would be a subroutine.The Form object could be found based on a ContainsKey. The rest of the ShowOrActiveForm function would be...
by Vladimir Vorobiev
This example contains the code to manage the menu of open forms (standard Windows menu). When created, each mdi-child gets a menu item and event handler through which this element is removed from the menu when the corresponding form is closed.private void ShowOrCreateMdiChild(Type formType)...
by Rafał Klepacz
private void OpenForm() where T : Form, new(){ T frm = (T)new List(this.MdiChildren).Find(f => f is T) ?? new T() { MdiParent = this }; frm.Show(); frm.Focus();}and usageOpenForm();
by PIEBALDconsult
Getting the line and position of the cursor in a TextBox
by PIEBALDconsult
OK, here's another way (I found this at http://dotnet.mvps.org/dotnet/faqs/?id=textboxcaretpos&lang=en[^]). [System.Runtime.InteropServices.StructLayoutAttribute (System.Runtime.InteropServices.LayoutKind.Sequential)]private struct ApiXY{ public int X ; public int Y ;}[ ...
by Brian C Hart
This tip shows how to add support for New Horizontal Tab Group and New Vertical Tab Group commands to the Window menu of an application using the DockPanel Suite by Weifen Luo, and some other minor improvements to help decided if at least one of your windows is docked to the side of the main form an
by Vercas
Unfocusable, borderless form, perfect for floating controls!
by AnuragTripathi
Convertor for Unicode to Krutidev and vice-versa.
by Awesh Vishwakarma
By reading this trick, you will be able to update your database from DataGridView through external class instead of writing code on each page.
by #realJSOP
When you need to communicate with the app that contains your ServiceHost object, use custom events
by Yvan Rodrigues
by honey the codewitch
This tip shows you how to do UI updates without having to worry about locking.
by Jacky Yiu
Visual cryptography is a cryptographic technique which allows visual information (pictures, text, etc.) to be encrypted in such a way that the decryption can be performed by the human visual system, without the aid of computers.
by kris444
Showing progress bar while performing time consume processes.
by Anshul R
You can use BackgroundWorker to do the work and report the progress using:private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){ this.progressBar1.Value = e.ProgressPercentage;}
by Bruce Lee Harrison
The background method is probably the most preferred method, but I've found this one is very easy to implement, and it's just one short line:BeginInvoke(new Action(() => progressBar1.Increment(1)));Place this in your worker thread to report to the UI. Not sure how "good" this is, but it...
by Member 147785
Hello!Here is a small article - Show progress on long-running operations, which describes approach to keep the UI responsive, starting long-running operations in separate thread. This approach is native and without any 3d-party libraries and even without BackgroundWorker.For example, the...
by Ron Levy
WebCam Application with Scheduling
by Chakravarthi Elchuri
How to use WIA supported scanner using C#
by IKalai
A Windows Forms toggle button with Android, Windows and iOS like styles.
by Clivic TR
This are a practical ways to confine inputs into a specific range. The natural thinking is to track them and change. That derives two ways below.
by mohanaitec
WinForm DataGridView loading from ObjectCollection.
by Jo_vb.net
My idea was to host a WPF user control with Ribbon within a WinForm VB.NET project and try to use MVVM pattern.
by Jamie Highfield
WinForms .NET Time Chooser grid control.
by Manish K. Agarwal
Simple Numeric TextBox to accept digits for a given minimum maximum range
by Tom Clement
A few notes on this code: Wouldn't you get an exception if the user happens to put in a number bigger than can be stored in an int32? Wouldn't int32.TryParse be better because of this?The control can be initialized with a negative number as a constraint, but it doesn't permit the '-'...
by Grasshopper.iics
I will use a label with font color red just below the text box and will adopt the following code private void textBox1_TextChanged(object sender, EventArgs e) { int min=0,max=256; try { label1.Visible = false; ...
by Nanda Kumar Chintam
Demonstration of Excel manipulations using C#
by adriancs
An Office 2010 Style Color Picker for .NET WinForm.