diff --git a/.openpublishing.redirection.json b/.openpublishing.redirection.json new file mode 100644 index 0000000000..58eb70c2f3 --- /dev/null +++ b/.openpublishing.redirection.json @@ -0,0 +1,208 @@ +{ + "redirections": [ + { + "source_path": "dotnet-desktop-guide/net/winforms/windows-forms-overview.md", + "redirect_url": "/dotnet/desktop/winforms/overview/?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/overview/index.md", + "redirect_url": "/dotnet/desktop/winforms/windows-forms-overview?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-create-a-windows-forms-application-from-the-command-line.md", + "redirect_url": "/dotnet/desktop/winforms/get-started/create-app-visual-studio?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/get-started/create-app-visual-studio.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-create-a-windows-forms-application-from-the-command-line?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/events-overview-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/forms/events?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/forms/events.md", + "redirect_url": "/dotnet/desktop/winforms/creating-event-handlers-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/automatic-scaling-in-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/forms/autoscale?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/forms/autoscale.md", + "redirect_url": "/dotnet/desktop/winforms/automatic-scaling-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-resize-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/forms/how-to-position-and-resize?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/forms/how-to-position-and-resize.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-resize-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/layout-in-windows-forms-controls.md", + "redirect_url": "/dotnet/desktop/winforms/controls/layout?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/layout.md", + "redirect_url": "/dotnet/desktop/winforms/controls/layout-in-windows-forms-controls?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/label-control-overview-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/controls/labels?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/labels.md", + "redirect_url": "/dotnet/desktop/winforms/controls/label-control-overview-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/varieties-of-custom-controls.md", + "redirect_url": "/dotnet/desktop/winforms/controls/custom?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/custom.md", + "redirect_url": "/dotnet/desktop/winforms/controls/control-type-recommendations?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/custom-control-painting-and-rendering.md", + "redirect_url": "/dotnet/desktop/winforms/controls/custom-painting-drawing?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/custom-painting-drawing.md", + "redirect_url": "/dotnet/desktop/winforms/controls/user-drawn-controls?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/how-to-add-controls-to-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-add-to-a-form?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/how-to-add-to-a-form.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-add-controls-to-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/how-to-create-access-keys-for-windows-forms-controls.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-create-access-keys?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-create-access-keys-for-windows-forms-controls?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/how-to-set-the-text-displayed-by-a-windows-forms-control.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-set-the-display-text?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-display-text.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-set-the-text-displayed-by-a-windows-forms-control?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/controls/how-to-set-the-image-displayed-by-a-windows-forms-control.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-add-a-picture-to-a-control?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-picture-to-a-control.md", + "redirect_url": "/dotnet/desktop/winforms/controls/how-to-set-the-image-displayed-by-a-windows-forms-control?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/keyboard-input-in-a-windows-forms-application.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/overview?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/overview.md", + "redirect_url": "/dotnet/desktop/winforms/how-keyboard-input-works?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/using-keyboard-events.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/events?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/events.md", + "redirect_url": "/dotnet/desktop/winforms/using-keyboard-events?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/user-input-validation-in-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/validation?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/validation.md", + "redirect_url": "/dotnet/desktop/winforms/user-input-validation-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-modify-keyboard-input-to-a-standard-control.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/how-to-change-key-press?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/how-to-change-key-press.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-modify-keyboard-input-to-a-standard-control?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-determine-which-modifier-key-was-pressed.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/how-to-check-modifier-key?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/how-to-check-modifier-key.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-determine-which-modifier-key-was-pressed?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-handle-keyboard-input-at-the-form-level.md", + "redirect_url": "/dotnet/desktop/winforms/input-keyboard/how-to-handle-forms?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/how-to-handle-forms.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-handle-keyboard-input-at-the-form-level?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-keyboard/how-to-simulate-events.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-simulate-mouse-and-keyboard-events-in-code?view=netframeworkdesktop-4.8#simulating-keyboard-input" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/mouse-input-in-a-windows-forms-application.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/overview?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/overview.md", + "redirect_url": "/dotnet/desktop/winforms/how-mouse-input-works-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/mouse-events-in-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/events?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/events.md", + "redirect_url": "/dotnet/desktop/winforms/mouse-events-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/drag-and-drop-functionality-in-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/drag-and-drop?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/drag-and-drop.md", + "redirect_url": "/dotnet/desktop/winforms/drag-and-drop-functionality-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/mouse-pointers-in-windows-forms.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/how-to-manage-cursor-pointer?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/how-to-manage-cursor-pointer.md", + "redirect_url": "/dotnet/desktop/winforms/mouse-pointers-in-windows-forms?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-simulate-mouse-and-keyboard-events-in-code.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/how-to-simulate-events?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/how-to-simulate-events.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-simulate-mouse-and-keyboard-events-in-code?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/winforms/how-to-distinguish-between-clicks-and-double-clicks.md", + "redirect_url": "/dotnet/desktop/winforms/input-mouse/how-to-distinguish-between-clicks-and-double-clicks?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/winforms/input-mouse/how-to-distinguish-between-clicks-and-double-clicks.md", + "redirect_url": "/dotnet/desktop/winforms/how-to-distinguish-between-clicks-and-double-clicks?view=netframeworkdesktop-4.8" + } + ] +} \ No newline at end of file diff --git a/dotnet-desktop-guide/TOC.yml b/dotnet-desktop-guide/TOC.yml index 3b9a23733e..9f6b9ddc4c 100644 --- a/dotnet-desktop-guide/TOC.yml +++ b/dotnet-desktop-guide/TOC.yml @@ -3,7 +3,7 @@ items: expanded: true items: - name: ".NET 5 (and .NET Core 3.1)" - href: net/winforms/index.md?view=netdesktop-5.0&preserve-view=true + href: net/winforms/index.yml?view=netdesktop-5.0&preserve-view=true - name: .NET Framework href: framework/winforms/index.yml?view=netframeworkdesktop-4.8&preserve-view=true - name: Windows Presentation Foundation diff --git a/dotnet-desktop-guide/docfx.json b/dotnet-desktop-guide/docfx.json index 125b4899a1..11cad5c56d 100644 --- a/dotnet-desktop-guide/docfx.json +++ b/dotnet-desktop-guide/docfx.json @@ -160,7 +160,8 @@ "xaml-services/**/*.md": "dotnet-desktop" }, "ms.topic": { - "xaml-services/**/*.md": "reference" + "xaml-services/**/*.md": "reference", + "**/*how-to*.md": "how-to" } }, "template": [], diff --git a/dotnet-desktop-guide/index.md b/dotnet-desktop-guide/index.md deleted file mode 100644 index 9063c8e7ab..0000000000 --- a/dotnet-desktop-guide/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Desktop Guide for WPF and Windows Forms -description: Introduction to the Desktop Guide for WPF and Windows Forms for both .NET 5 and .NET Framework. -ms.prod: dotnet-desktop -ms.date: "08/30/2020" ---- - -# Desktop Guide for .NET, .NET Core, and .NET Framework - -Welcome to the Desktop Guide. The Desktop Guide is a set of documentation for .NET-based Windows UI technologies including Windows Presentation Foundation (WPF) and Windows Forms (WinForms). The Desktop Guide will cover both .NET 5 (and .NET Core 3.1) and later versions, along with .NET Framework. - -Historically, the .NET Framework-based documentation for WPF and WinForms has been included in the [.NET Documentation](/dotnet). Windows Forms content has been migrated to this guide, while the migration of WPF content is ongoing. - -## Windows Presentation Foundation - -There are two implementations of WPF, each with it's own documentation: - -01. The [.NET Framework 4 implementation](framework/wpf/index.md?view=netframeworkdesktop-4.8&preserve-view=true) that's supported by Visual Studio 2019 and Visual Studio 2017. - - .NET Framework 4 is a Windows-only version of .NET and is considered a Windows Operating System component. This version of Windows Presentation Foundation is distributed with .NET Framework. - - The documentation for this version of WPF is available [here](framework/wpf/index.md?view=netframeworkdesktop-4.8&preserve-view=true). - -01. The open-source implementation hosted on [GitHub](https://github.com/dotnet/wpf). - - This version runs on **.NET 5 and .NET Core 3.1**. The WPF XAML Visual Designer requires, at a minimum, [Visual Studio 2019 version 16.X](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms). - - Even though this version of .NET is cross-platform, WPF remains a Windows-only technology. - - The documentation for this version of WPF is in progress and is available [here](net/wpf/index.yml?view=netdesktop-5.0&preserve-view=true). - -## Windows Forms - -There are two implementations of Windows Forms, each with it's own documentation: - -01. The [.NET Framework 4 implementation](framework/winforms/index.yml?view=netframeworkdesktop-4.8&preserve-view=true) that's supported by Visual Studio 2019 and Visual Studio 2017. - - .NET Framework 4 is a Windows-only version of .NET and is considered a Windows Operating System component. This version of WinForms is distributed with .NET Framework. - - The documentation for this version of WinForms is available [here](framework/winforms/index.yml?view=netframeworkdesktop-4.8&preserve-view=true). - -01. The open-source implementation hosted on [GitHub](https://github.com/dotnet/winforms). - - This version runs on **.NET 5 and .NET Core 3.1**. The Windows Forms Visual Designer requires, at a minimum, [Visual Studio 2019 version 16.X](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms). - - Even though this version of .NET is cross-platform, WinForms remains a Windows-only technology. - - The documentation for this version of WinForms is in progress and not yet available. diff --git a/dotnet-desktop-guide/index.yml b/dotnet-desktop-guide/index.yml new file mode 100644 index 0000000000..95e03bfa9b --- /dev/null +++ b/dotnet-desktop-guide/index.yml @@ -0,0 +1,50 @@ +### YamlMime:Landing + +title: Desktop Guide for .NET, .NET Core, and .NET Framework +summary: "Welcome to the Desktop Guide. The Desktop Guide is a set of documentation for .NET-based Windows UI technologies including Windows Presentation Foundation (WPF) and Windows Forms (WinForms). The Desktop Guide will cover both .NET 5 (and .NET Core 3.1) and later versions, along with .NET Framework." + +metadata: + title: Desktop Guide for WPF and Windows Forms on .NET + description: Introduction to the Desktop Guide for WPF and Windows Forms for both .NET 5 and .NET Framework. + ms.topic: landing-page + ms.product: dotnet + author: adegeo + ms.author: adegeo + ms.date: 10/21/2020 + +# linkListType: architecture | concept | deploy | download | get-started | how-to-guide | learn | overview | quickstart | reference | sample | tutorial | video | whats-new + +landingContent: + +- title: .NET 5 (and .NET Core 3.1) + linkLists: + - linkListType: overview + links: + - text: Windows Presentation Foundation (WPF) + url: net/wpf/index.yml?view=netdesktop-5.0&preserve-view=true + - text: Windows Forms (WinForms) + url: net/winforms/index.yml?view=netdesktop-5.0&preserve-view=true + +- title: .NET Framework + linkLists: + - linkListType: overview + links: + - text: Windows Presentation Foundation (WPF) + url: framework/wpf/index.md?view=netframeworkdesktop-4.8&preserve-view=true + - text: Windows Forms (WinForms) + url: framework/winforms/index.yml?view=netframeworkdesktop-4.8&preserve-view=true + - linkListType: concept + links: + - text: Introduction to WPF + url: framework/wpf/introduction-to-wpf.md?view=netframeworkdesktop-4.8&preserve-view=true + - text: Introduction to WinForms + url: framework/winforms/windows-forms-overview.md?view=netframeworkdesktop-4.8&preserve-view=true + +- title: Other desktop technologies + linkLists: + - linkListType: overview + links: + - text: Universal Windows Apps + url: /uwp + - text: Xamarin Forms + url: /xamarin/xamarin-forms/ diff --git a/dotnet-desktop-guide/net/winforms/controls/custom-painting-drawing.md b/dotnet-desktop-guide/net/winforms/controls/custom-painting-drawing.md new file mode 100644 index 0000000000..196f70f890 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/custom-painting-drawing.md @@ -0,0 +1,125 @@ +--- +title: Custom painting for a control +description: Learn about how to customize the appearance of a control through the OnPaint method and Paint event in Windows Forms for .NET. +ms.date: 10/26/2020 +ms.topic: overview +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "OnPaint" +helpviewer_keywords: + - "controls [Windows Forms], user controls" + - "controls [Windows Forms], types of" + - "composite controls [Windows Forms]" + - "extended controls [Windows Forms]" + - "controls [Windows Forms], extended" + - "user controls [Windows Forms]" + - "custom controls [Windows Forms]" + - "controls [Windows Forms], composite" +--- + +# Painting and drawing on controls (Windows Forms .NET) + +Custom painting of controls is one of the many complicated tasks made easy by Windows Forms. When authoring a custom control, you have many options available to handle your control's graphical appearance. If you're authoring a [custom control](custom.md#custom-controls), that is, a control that inherits from , you must provide code to render its graphical representation. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +If you're creating a [composite control](custom.md#composite-controls), that is a control that inherits from or one of the existing Windows Forms controls, you may override the standard graphical representation and provide your own graphics code. + +If you want to provide custom rendering for an existing control without creating a new control, your options become more limited. However, there are still a wide range of graphical possibilities for your controls and applications. + +The following elements are involved in control rendering: + +- The drawing functionality provided by the base class . +- The essential elements of the GDI graphics library. +- The geometry of the drawing region. +- The procedure for freeing graphics resources. + +## Drawing provided by control + +The base class provides drawing functionality through its event. A control raises the event whenever it needs to update its display. For more information about events in the .NET, see [Handling and raising events](/dotnet/standard/events/index). + +The event data class for the event, , holds the data needed for drawing a control - a handle to a graphics object and a rectangle that represents the region to draw in. + +```csharp +public class PaintEventArgs : EventArgs, IDisposable +{ + + public System.Drawing.Rectangle ClipRectangle {get;} + public System.Drawing.Graphics Graphics {get;} + + // Other properties and methods. +} +``` + +```vb +Public Class PaintEventArgs + Inherits EventArgs + Implements IDisposable + + Public ReadOnly Property ClipRectangle As System.Drawing.Rectangle + Public ReadOnly Property Graphics As System.Drawing.Graphics + + ' Other properties and methods. +End Class +``` + + is a managed class that encapsulates drawing functionality, as described in the discussion of GDI later in this article. The is an instance of the structure and defines the available area in which a control can draw. A control developer can compute the using the property of a control, as described in the discussion of geometry later in this article. + +### OnPaint + +A control must provide rendering logic by overriding the method that it inherits from . gets access to a graphics object and a rectangle to draw in through the and the properties of the instance passed to it. + +The following code uses the `System.Drawing` namespace: + +:::code language="csharp" source="./snippets/custom-painting-drawing/cs/UserControl1.cs" id="OnPaintMethod"::: + +:::code language="vb" source="./snippets/custom-painting-drawing/vb/UserControl1.vb" id="OnPaintMethod"::: + +The method of the base class doesn't implement any drawing functionality but merely invokes the event delegates that are registered with the event. When you override , you should typically invoke the method of the base class so that registered delegates receive the event. However, controls that paint their entire surface shouldn't invoke the base class's , as this introduces flicker. + +> [!NOTE] +> Don't invoke directly from your control; instead, invoke the method (inherited from ) or some other method that invokes . The method in turn invokes . The method is overloaded, and, depending on the arguments supplied to `e`, redraws either some or all of its screen area. + +The code in the method of your control will execute when the control is first drawn, and whenever it is refreshed. To ensure that your control is redrawn every time it is resized, add the following line to the constructor of your control: + +```csharp +SetStyle(ControlStyles.ResizeRedraw, true); +``` + +```vb +SetStyle(ControlStyles.ResizeRedraw, True) +``` + +### OnPaintBackground + +The base class defines another method that is useful for drawing, the method. + +```csharp +protected virtual void OnPaintBackground(PaintEventArgs e); +``` + +```vb +Protected Overridable Sub OnPaintBackground(e As PaintEventArgs) +``` + + paints the background (and in that way, the shape) of the window and is guaranteed to be fast, while paints the details and might be slower because individual paint requests are combined into one event that covers all areas that have to be redrawn. You might want to invoke the if, for instance, you want to draw a gradient-colored background for your control. + +While has an event-like nomenclature and takes the same argument as the `OnPaint` method, `OnPaintBackground` is not a true event method. There is no `PaintBackground` event and `OnPaintBackground` doesn't invoke event delegates. When overriding the `OnPaintBackground` method, a derived class is not required to invoke the `OnPaintBackground` method of its base class. + +## GDI+ Basics + +The class provides methods for drawing various shapes such as circles, triangles, arcs, and ellipses, and methods for displaying text. The namespace contains namespaces and classes that encapsulate graphics elements such as shapes (circles, rectangles, arcs, and others), colors, fonts, brushes, and so on. + +## Geometry of the Drawing Region + +The property of a control specifies the rectangular region available to the control on the user's screen, while the property of specifies the area that is painted. A control might need to paint only a portion of its available area, as is the case when a small section of the control's display changes. In those situations, a control developer must compute the actual rectangle to draw in and pass that to . The overloaded versions of that take a or as an argument use that argument to generate the property of . + +## Freeing Graphics Resources + +Graphics objects are expensive because they use system resources. Such objects include instances of the class and instances of , , and other graphics classes. It's important that you create a graphics resource only when you need it and release it soon as you're finished using it. If you create an instance of a type that implements the interface, call its method when you're finished with it to free resources. + +## See also + +- [Types of custom controls](custom.md) diff --git a/dotnet-desktop-guide/net/winforms/controls/custom.md b/dotnet-desktop-guide/net/winforms/controls/custom.md new file mode 100644 index 0000000000..d95b6b2397 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/custom.md @@ -0,0 +1,133 @@ +--- +title: Types of custom controls +description: Learn about the different types of custom controls you can create in Windows Forms for .NET. +ms.date: 10/26/2020 +ms.topic: overview +f1_keywords: + - "UserControl" +helpviewer_keywords: + - "controls [Windows Forms], user controls" + - "controls [Windows Forms], types of" + - "composite controls [Windows Forms]" + - "extended controls [Windows Forms]" + - "controls [Windows Forms], extended" + - "user controls [Windows Forms]" + - "custom controls [Windows Forms]" + - "controls [Windows Forms], composite" +--- + +# Types of custom controls (Windows Forms .NET) + +With Windows Forms, you can develop and implement new controls. You can create a new user control, modify existing controls through inheritance, and write a custom control that does its own painting. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +Deciding which kind of control to create can be confusing. This article highlights the differences among the various kinds of controls from which you can inherit, and provides you with information about how to choose a particular type of control for your project. + + + + + + + + + + + + + + + + + + + + + + +
If ...Create a ...
+
    +
  • You want to combine the functionality of several Windows Forms controls into a single reusable unit.
  • +
+
Composite control by inheriting from System.Windows.Forms.UserControl.
+
    +
  • Most of the functionality you need is already identical to an existing Windows Forms control.
  • +
  • You don't need a custom graphical user interface, or you want to design a new graphical user interface for an existing control.
  • +
+
Extended control by inheriting from a specific Windows Forms control.
+
    +
  • You want to provide a custom graphical representation of your control.
  • +
  • You need to implement custom functionality that isn't available through standard controls.
  • +
+
Custom control by inheriting from System.Windows.Forms.Control.
+ +## Base Control Class + +The class is the base class for Windows Forms controls. It provides the infrastructure required for visual display in Windows Forms applications and provides the following capabilities: + +- Exposes a window handle. +- Manages message routing. +- Provides mouse and keyboard events, and many other user interface events. +- Provides advanced layout features. +- Contains many properties specific to visual display, such as , , , and . +- Provides the security and threading support necessary for a Windows Forms control to act as a Microsoft® ActiveX® control. + +Because so much of the infrastructure is provided by the base class, it's relatively easy to develop your own Windows Forms controls. + +## Composite Controls + +A composite control is a collection of Windows Forms controls encapsulated in a common container. This kind of control is sometimes called a *user control*. The contained controls are called *constituent controls*. + +A composite control holds all of the inherent functionality associated with each of the contained Windows Forms controls and enables you to selectively expose and bind their properties. A composite control also provides a great deal of default keyboard handling functionality with no extra development effort on your part. + +For example, a composite control could be built to display customer address data from a database. This control would include a control to display the database fields, a to handle binding to a data source, and a control to move through the records. You could selectively expose data binding properties, and you could package and reuse the entire control from application to application. + +To author a composite control, derive from the class. The base class provides keyboard routing for child controls and enables child controls to work as a group. + +## Extended Controls + +You can derive an inherited control from any existing Windows Forms control. With this approach, you can keep all of the inherent functionality of a Windows Forms control, and then extend that functionality by adding custom properties, methods, or other features. With this option, you can override the base control's paint logic, and then extend its user interface by changing its appearance. + +For example, you can create a control derived from the control that tracks how many times a user has clicked it. + +In some controls, you can also add a custom appearance to the graphical user interface of your control by overriding the method of the base class. For an extended button that tracks clicks, you can override the method to call the base implementation of , and then draw the click count in one corner of the control's client area. + +## Custom Controls + +Another way to create a control is to create one substantially from the beginning by inheriting from . The class provides all of the basic functionality required by controls, including mouse and keyboard handling events, but no control-specific functionality or graphical interface. + +Creating a control by inheriting from the class requires much more thought and effort than inheriting from or an existing Windows Forms control. Because a great deal of implementation is left for you, your control can have greater flexibility than a composite or extended control, and you can tailor your control to suit your exact needs. + +To implement a custom control, you must write code for the event of the control, as well as any feature-specific code you need. You can also override the method and handle windows messages directly. This is the most powerful way to create a control, but to use this technique effectively, you need to be familiar with the Microsoft Win32® API. + +An example of a custom control is a clock control that duplicates the appearance and behavior of an analog clock. Custom painting is invoked to cause the hands of the clock to move in response to events from an internal component. + +## ActiveX Controls + +Although the Windows Forms infrastructure has been optimized to host Windows Forms controls, you can still use ActiveX controls. There's support for this task in Visual Studio. + +## Windowless Controls + +The Microsoft Visual Basic® 6.0 and ActiveX technologies support *windowless* controls. Windowless controls aren't supported in Windows Forms. + +## Custom Design Experience + +If you need to implement a custom design-time experience, you can author your own designer. For composite controls, derive your custom designer class from the or the classes. For extended and custom controls, derive your custom designer class from the class. + +Use the to associate your control with your designer. + +The following information is out of date but may help you. + +- [(Visual Studio 2013) Extending Design-Time Support](/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)). +- [(Visual Studio 2013) How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)). + +## See also + +- [Overview of Using Controls (Windows Forms .NET)](overview.md) + + diff --git a/dotnet-desktop-guide/net/winforms/controls/how-to-add-a-picture-to-a-control.md b/dotnet-desktop-guide/net/winforms/controls/how-to-add-a-picture-to-a-control.md new file mode 100644 index 0000000000..02ab1bb45f --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/how-to-add-a-picture-to-a-control.md @@ -0,0 +1,55 @@ +--- +title: Display an image on a control +description: Learn how to display an image on a Windows Form control. Many controls, such as the PictureBox, can display an image. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Button control [Windows Forms], images" + - "Windows Forms controls, images" + - "controls [Windows Forms], images" + - "images [Windows Forms], Windows Forms contr ols" + - "examples [Windows Forms], controls" +--- + +# How to display an image on a control (Windows Forms .NET) + +Several Windows Forms controls can display images. These images can be icons that clarify the purpose of the control, such as a diskette icon on a button denoting the Save command. Alternatively, the icons can be background images to give the control the appearance and behavior you want. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Designer + +In the **Properties** window of Visual Studio, select the **Image** or **BackgroundImage** property of the control, and then select the ellipsis (![Ellipsis button in Visual Studio](../media/visual-studio-ellipsis-button.png)) to display the **Select Resource** dialog box and then select the image you want to display. + +:::image type="content" source="media/how-to-add-a-picture-to-a-control/properties-image.png" alt-text="Properties dialog with image property selected"::: + +## Programmatic + +Set the control's `Image` or `BackgroundImage` property to an object of type . Generally, you'll be loading the image from a file by using the method. + +In the following code example, the path set for the location of the image is the **My Pictures** folder. Most computers running the Windows operating system include this directory. This also enables users with minimal system access levels to run the application safely. The following code example requires that you already have a form with a control added. + +```csharp +// Replace the image named below with your own icon. +// Note the escape character used (@) when specifying the path. +pictureBox1.Image = Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.MyPictures) + + @"\Image.gif"); +``` + +```vb +' Replace the image named below with your own icon. +PictureBox1.Image = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.MyPictures) _ + & "\Image.gif") +``` + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/controls/how-to-add-to-a-form.md b/dotnet-desktop-guide/net/winforms/controls/how-to-add-to-a-form.md new file mode 100644 index 0000000000..0cb30314ae --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/how-to-add-to-a-form.md @@ -0,0 +1,53 @@ +--- +title: Add Controls to a Form +description: Learn how to add a control a form in Windows Forms for .NET +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms controls, adding to form" + - "controls [Windows Forms], adding" +--- + +# Add a control (Windows Forms .NET) + +Most forms are designed by adding controls to the surface of the form to define a user interface (UI). A *control* is a component on a form used to display information or accept user input. + +The primary way a control is added to a form is through the Visual Studio Designer, but you can also manage the controls on a form at run time through code. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Add with Designer + +Visual Studio uses the Forms Designer to design forms. There is a Controls pane which lists all the controls available to your app. You can add controls from the pane in two ways: + +### Add the control by double-clicking + +When a control is double-clicked, it is automatically added to the current open form with default settings. + +:::image type="content" source="media/how-to-add-to-a-form/toolbox-double-click.gif" alt-text="Double-click a control in the toolbox on visual studio for .NET Windows Forms"::: + +### Add the control by drawing + +Select the control by clicking on it. In your form, drag-select a region. The control will be placed to fit the size of the region you selected. + +:::image type="content" source="media/how-to-add-to-a-form/toolbox-drag-draw.gif" alt-text="Drag-select and draw a control from the toolbox on visual studio for .NET Windows Forms"::: + +## Add with code + +Controls can be created and then added to a form at run time with the form's collection. This collection can also be used to remove controls from a form. + +The following code adds and positions two controls, a [Label](xref:System.Windows.Forms.Label) and a [TextBox](xref:System.Windows.Forms.TextBox): + +:::code language="csharp" source="snippets/how-to-add-to-a-form/cs/Form1.cs" id="CreateControl"::: + +:::code language="vb" source="snippets/how-to-add-to-a-form/vb/Form1.vb" id="CreateControl"::: + +## See also + +- [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-display-text.md) +- [How to: Add an access key shortcut to a control](how-to-create-access-keys.md) +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/controls/how-to-create-access-keys.md b/dotnet-desktop-guide/net/winforms/controls/how-to-create-access-keys.md new file mode 100644 index 0000000000..e26bc049ef --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/how-to-create-access-keys.md @@ -0,0 +1,91 @@ +--- +title: Create Access Keys for Controls +description: Learn how to set the access key shortcut on a control or label in Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], access keys" + - "Button control [Windows Forms], access keys" + - "dialog box controls [Windows Forms], mnemonics" + - "access keys [Windows Forms], creating for controls" + - "mnemonics" + - "ampersand character in shortcut key" + - "Windows Forms controls, access keys" + - "examples [Windows Forms], controls" + - "Text property [Windows Forms], specifying access keys for controls" + - "keyboard shortcuts [Windows Forms], creating for controls" + - "access keys [Windows Forms], Windows Forms" + - "ALT key" +--- + +# Add an access key shortcut to a control (Windows Forms .NET) + +An *access key* is an underlined character in the text of a menu, menu item, or the label of a control such as a button. With an access key, the user can "click" a button by pressing the Alt key in combination with the predefined access key. For example, if a button runs a procedure to print a form, and therefore its `Text` property is set to "Print," adding an ampersand (&) before the letter "P" causes the letter "P" to be underlined in the button text at run time. The user can run the command associated with the button by pressing Alt. + +Controls that cannot receive focus can't have access keys, except label controls. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Designer + +In the **Properties** window of Visual Studio, set the **Text** property to a string that includes an ampersand (&) before the letter that will be the access key. For example, to set the letter "P" as the access key, enter **&Print**. + +:::image type="content" source="media/how-to-create-access-keys/properties-text.png" alt-text="Properties dialog with text property selected and access key"::: + +## Programmatic + +Set the `Text` property to a string that includes an ampersand (&) before the letter that will be the shortcut. + +```vb +' Set the letter "P" as an access key. +Button1.Text = "&Print" +``` + +```csharp +// Set the letter "P" as an access key. +button1.Text = "&Print"; +``` + +## Use a label to focus a control + +Even though a label cannot be focused, it has the ability to focus the next control in the tab order of the form. Each control is assigned a value to the property, generally in ascending sequential order. When the access key is assigned to the [Label.Text](xref:System.Windows.Forms.Label.Text) property, the next control in the sequential tab order is focused. + +Using the example from the [Programmatic](#programmatic) section, if the button didn't have any text set, but instead presented an image of a printer, you could use a label to focus the button. + +```vb +' Set the letter "P" as an access key. +Label1.Text = "&Print" +Label1.TabIndex = 9 +Button1.TabIndex = 10 +``` + +```csharp +// Set the letter "P" as an access key. +label1.Text = "&Print"; +label1.TabIndex = 9 +button1.TabIndex = 10 +``` + +## Display an ampersand + +When setting the text or caption of a control that interprets an ampersand (&) as an access key, use two consecutive ampersands (&&) to display a single ampersand. For example, the text of a button set to `"Print && Close"` displays in the caption of `Print & Close`: + +```vb +' Set the letter "P" as an access key. +Button1.Text = "Print && Close" +``` + +```csharp +// Set the letter "P" as an access key. +button1.Text = "Print && Close"; +``` + +:::image type="content" source="media/how-to-create-access-keys/double-ampersand.png" alt-text="displaying an ampersand in a button"::: + +## See also + +- [How to: Set the text displayed by a Windows Forms control](how-to-set-the-display-text.md) +- +- diff --git a/dotnet-desktop-guide/net/winforms/controls/how-to-set-the-display-text.md b/dotnet-desktop-guide/net/winforms/controls/how-to-set-the-display-text.md new file mode 100644 index 0000000000..932e67c9fb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/how-to-set-the-display-text.md @@ -0,0 +1,80 @@ +--- +title: Set the Text displayed by a Control +description: Learn how to set the text displayed by a Windows Forms control. Set or return the text by using the Text property, or change the font by using the Font property. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, captions" + - "Button control [Windows Forms], button text" + - "StdFont object and CommandButton caption" + - "captions [Windows Forms], Windows Forms controls" + - "Text property [Windows Forms], Windows Forms control" + - "Button control [Windows Forms], text display" + - "labels [Windows Forms], adding to CommandButton control" + - "buttons [Windows Forms], text" + - "captions [Windows Forms], setting" + - "text" + - "examples [Windows Forms], controls" + - "text [Windows Forms], Windows Forms controls" + - "controls [Windows Forms], captions" + - "forms [Windows Forms], captions" +--- +# How to: Set the text displayed by a control (Windows Forms .NET) + +Windows Forms controls usually display some text that's related to the primary function of the control. For example, a control usually displays a caption indicating what action will be performed if the button is clicked. For all controls, you can set or return the text by using the property. You can change the font by using the property. + +You can also set the text by using the [designer](#designer). + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Designer + +01. In the **Properties** window in Visual Studio, set the **Text** property of the control to an appropriate string. + + To create an underlined shortcut key, include an ampersand (&) before the letter that will be the shortcut key. + + :::image type="content" source="media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-text.png" alt-text="Visual Studio Properties pane for .NET Windows Forms with Text property shown."::: + +01. In the **Properties** window, select the ellipsis button (![Ellipsis button (...) in the Properties window of Visual Studio](../media/visual-studio-ellipsis-button.png)) next to the **Font** property. + + :::image type="content" source="media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-font.png" alt-text="Visual Studio Properties pane for .NET Windows Forms with Font property shown."::: + + In the standard font dialog box, adjust the font with settings such as type, size, and style. + + :::image type="content" source="media/how-to-set-the-text-displayed-by-a-windows-forms-control/font-window.png" alt-text="Visual Studio Properties pane for .NET Windows Forms with Font settings window."::: + +## Programmatic + +01. Set the property to a string. + + To create an underlined access key, include an ampersand (&) before the letter that will be the access key. + +01. Set the property to an object of type . + + ```vb + Button1.Text = "Click here to save changes" + Button1.Font = New Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Point) + ``` + + ```csharp + button1.Text = "Click here to save changes"; + button1.Font = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Point); + ``` + + > [!NOTE] + > You can use an escape character to display a special character in user-interface elements that would normally interpret them differently, such as menu items. For example, the following line of code sets the menu item's text to read "& Now For Something Completely Different": + + ```vb + MPMenuItem.Text = "&& Now For Something Completely Different" + ``` + + ```csharp + mpMenuItem.Text = "&& Now For Something Completely Different"; + ``` + +## See also + +- +- [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys.md) diff --git a/dotnet-desktop-guide/net/winforms/controls/labels.md b/dotnet-desktop-guide/net/winforms/controls/labels.md new file mode 100644 index 0000000000..85cc980f92 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/labels.md @@ -0,0 +1,33 @@ +--- +title: Label control +description: Learn about the Label control in Windows Forms for .NET. Labels are used to identify visual elements to the user. +ms.date: 10/26/2020 +ms.topic: overview +f1_keywords: + - "Label" +helpviewer_keywords: + - "images [Windows Forms], displaying in labels" + - "labels" + - "Label control [Windows Forms], about Label control" +--- + +# Label control overview (Windows Forms .NET) + +Windows Forms controls are used to display text that cannot be edited by the user. They're used to identify objects on a form and to provide a description of what a certain control represents or does. For example, you can use labels to add descriptive captions to text boxes, list boxes, combo boxes, and so on. You can also write code that changes the text displayed by a label in response to events at run time. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Working with the Label Control + +Because the control can't receive focus, it can be used to create access keys for other controls. An access key allows a user to focus the next control in tab order by pressing the Alt key with the chosen access key. For more information, see [Use a label to focus a control](how-to-create-access-keys.md#use-a-label-to-focus-a-control). + +The caption displayed in the label is contained in the property. The property allows you to set the alignment of the text within the label. For more information, see [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-display-text.md). + +## See also + +- [Use a label to focus a control (Windows Forms .NET)](how-to-create-access-keys.md#use-a-label-to-focus-a-control) +- [How to: Set the text displayed by a control (Windows Forms .NET)](how-to-set-the-display-text.md) +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/controls/layout.md b/dotnet-desktop-guide/net/winforms/controls/layout.md new file mode 100644 index 0000000000..07d4cc2d2b --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/layout.md @@ -0,0 +1,169 @@ +--- +title: Control layout options +description: Learn about the different settings on a control that affect layout and positioning in Windows Forms for .NET. Learn about the different types of control containers that affect layout. +ms.date: 10/26/2020 +ms.topic: overview +helpviewer_keywords: + - "forms [Windows Forms], aligning controls" + - "Windows Forms, aligning controls" + - "controls [Windows Forms], positioning" + - "controls [Windows Forms], aligning" + - "TabControl control [Windows Forms], about TabControl control" + - "SplitContainer control [Windows Forms], about SplitContainer control" + - "Panel control [Windows Forms], about Panel control" + - "GroupBox control [Windows Forms], about GroupBox control" + - "FlowLayoutPanel control [Windows Forms], about FlowLayoutPanel control" + - "TableLayoutPanel control [Windows Forms], about TableLayoutPanel control" + - "sizing [Windows Forms], automatic" + - "layout [Windows Forms], AutoSize" + - "automatic sizing" + - "AutoSizeMode property" +--- + +# Position and layout of controls (Windows Forms .NET) + +Control placement in Windows Forms is determined not only by the control, but also by the parent of the control. This article describes the different settings provided by controls and the different types of parent containers that affect layout. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Fixed position and size + +The position a control appears on a parent is determined by the value of the property relative to the top-left of the parent surface. The top-left position coordinate in the parent is `(x0,y0)`. The size of the control is determined by the property and represents the width and height of the control. + +:::image type="content" source="media/layout/location+container.png" alt-text="Location of the control relative to the container"::: + +When a control is added to a parent that enforces automatic placement, the position and size of the control is changed. In this case, the position and size of the control may not be manually adjusted, depending on the type of parent. + +The and properties help set the minimum and maximum space a control can use. + +## Automatic placement and size + +Controls can be automatically placed within their parent. Some parent containers force placement while others respect control settings that guide placement. There are two properties on a control that help automatic placement and size within a parent: and . + +Drawing order can affect automatic placement. The order in which a control is drawn determined by the control's index in the parent's collection. This index is known as the **:::no-loc text="Z-order":::**. Each control is drawn in the reverse order they appear in the collection. Meaning, the collection is a first-in-last-drawn and last-in-first-drawn collection. + +The and properties help set the minimum and maximum space a control can use. + +### Dock + +The `Dock` property sets which border of the control is aligned to the corresponding side of the parent, and how the control is resized within the parent. + +:::image type="content" source="media/layout/dock-modes.png" alt-text="Windows form with buttons with dock settings."::: + +When a control is docked, the container determines the space it should occupy and resizes and places the control. The width and height of the control are still respected based on the docking style. For example, if the control is docked to the top, the of the control is respected but the is automatically adjusted. If a control is docked to the left, the of the control is respected but the is automatically adjusted. + +The of the control can't be manually set as docking a control automatically controls its position. + +The **:::no-loc text="Z-order":::** of the control does affect docking. As docked controls are laid out, they use what space is available to them. For example, if a control is drawn first and docked to the top, it will take up the entire width of the container. If a next control is docked to the left, it has less vertical space available to it. + +:::image type="content" source="media/layout/dock-top-then-left.png" alt-text="Windows form with buttons docked to the left and top with top being bigger."::: + +If the control's **:::no-loc text="Z-order":::** is reversed, the control that is docked to the left now has more initial space available. The control uses the entire height of the container. The control that is docked to the top has less horizontal space available to it. + +:::image type="content" source="media/layout/dock-left-then-top.png" alt-text="Windows form with buttons docked to the left and top with left being bigger."::: + +As the container grows and shrinks, the controls docked to the container are repositioned and resized to maintain their applicable positions and sizes. + +:::image type="content" source="media/layout/dock-resize.gif" alt-text="Animation showing how A Windows Form with buttons docked in all positions is resized."::: + +If multiple controls are docked to the same side of the container, they're stacked according to their **:::no-loc text="Z-order":::**. + +:::image type="content" source="media/layout/dock-left-left.png" alt-text="Windows form with two buttons docked to the left."::: + +### Anchor + +Anchoring a control allows you to tie the control to one or more sides of the parent container. As the container changes in size, any child control will maintain its distance to the anchored side. + +A control can be anchored to one or more sides, without restriction. The anchor is set with the property. + +:::image type="content" source="media/layout/anchor-resize.gif" alt-text="Animation showing how A Windows Form with buttons anchored in all positions is resized."::: + +### Automatic sizing + +The property enables a control to change its size, if necessary, to fit the size specified by the property. You adjust the sizing behavior for specific controls by setting the `AutoSizeMode` property. + +Only some controls support the property. In addition, some controls that support the property also supports the `AutoSizeMode` property. + +| Always true behavior | Description | +|--|--| +| Automatic sizing is a run-time feature. | This means it never grows or shrinks a control and then has no further effect. | +| If a control changes size, the value of its property always remains constant. | When a control's contents cause it to grow, the control grows toward the right and downward. Controls do not grow to the left. | +| The and properties are honored when is `true`. | The value of the control's property is adjusted to the correct value.

The control is the exception to this rule. When you set the value of a docked control's property to `true`, the control will not stretch. | +| A control's and properties are always honored, regardless of the value of its property. | The and properties are not affected by the property. | +| There is no minimum size set by default. | This means that if a control is set to shrink under and it has no contents, the value of its property is `(0x,0y)`. In this case, your control will shrink to a point, and it will not be readily visible. | +| If a control does not implement the method, the method returns last value assigned to the property. | This means that setting to `true` will have no effect. | +| A control in a cell always shrinks to fit in the cell until its is reached. | This size is enforced as a maximum size. This is not the case when the cell is part of an row or column. | + +## Container: Form + +The is the main object of Windows Forms. A Windows Forms application will usually have a form displayed at all times. Forms contain controls and respect the and properties of the control for manual placement. Forms also respond to the [Dock](#dock) property for automatic placement. + +Most of the time a form will have grips on the edges that allow the user to resize the form. The property of a control will let the control grow and shrink as the form is resized. + +## Container: Panel + +The control is similar to a form in that it simply groups controls together. It supports the same manual and automatic placement styles that a form does. For more information, see the [Container: Form](#container-form) section. + +A panel blends in seamlessly with the parent, and it does cut off any area of a control that falls out of bounds of the panel. If a control falls outside the bounds of the panel and is set to `true`, scroll bars appear and the user can scroll the panel. + +Unlike the [group box](#container-group-box) control, a panel doesn't have a caption and border. + +:::image type="content" source="media/layout/panel-groupbox.png" alt-text="A Windows Form with a panel and group box."::: + +The image above has a panel with the property set to demonstrate the bounds of the panel. + +## Container: Group box + +The control provides an identifiable grouping for other controls. Typically, you use a group box to subdivide a form by function. For example, you may have a form representing personal information and the fields related to an address would be grouped together. At design time, it's easy to move the group box around along with its contained controls. + +The group box supports the same manual and automatic placement styles that a form does. For more information, see the [Container: Form](#container-form) section. A group box also cuts off any portion of a control that falls out of bounds of the panel. + +Unlike the [panel](#container-panel) control, a group box doesn't have the capability to scroll content and display scroll bars. + +:::image type="content" source="media/layout/panel-groupbox.png" alt-text="A Windows Form with a panel and group box."::: + +## Container: Flow Layout + +The control arranges its contents in a horizontal or vertical flow direction. You can wrap the control's contents from one row to the next, or from one column to the next. Alternately, you can clip instead of wrap its contents. + +You can specify the flow direction by setting the value of the property. The control correctly reverses its flow direction in Right-to-Left (RTL) layouts. You can also specify whether the control's contents are wrapped or clipped by setting the value of the property. + +The control automatically sizes to its contents when you set the property to `true`. It also provides a `FlowBreak` property to its child controls. Setting the value of the `FlowBreak` property to `true` causes the control to stop laying out controls in the current flow direction and wrap to the next row or column. + +:::image type="content" source="media/layout/flow.png" alt-text="A Windows Form with two flow panel controls."::: + +The image above has two `FlowLayoutPanel` controls with the property set to demonstrate the bounds of the control. + +## Container: Table layout + +The control arranges its contents in a grid. Because the layout is done both at design time and run time, it can change dynamically as the application environment changes. This gives the controls in the panel the ability to resize proportionally, so they can respond to changes such as the parent control resizing or text length changing because of localization. + +Any Windows Forms control can be a child of the control, including other instances of . This allows you to construct sophisticated layouts that adapt to changes at run time. + +You can also control the direction of expansion (horizontal or vertical) after the control is full of child controls. By default, the control expands downward by adding rows. + +You can control the size and style of the rows and columns by using the and properties. You can set the properties of rows or columns individually. + +The control adds the following properties to its child controls: `Cell`, `Column`, `Row`, `ColumnSpan`, and `RowSpan`. + +:::image type="content" source="media/layout/table.png" alt-text="A Windows Form with table layout control."::: + +The image above has a table with the property set to demonstrate the bounds of each cell. + +## Container: Split container + +The Windows Forms control can be thought of as a composite control; it's two panels separated by a movable bar. When the mouse pointer is over the bar, the pointer changes shape to show that the bar is movable. + +With the control, you can create complex user interfaces; often, a selection in one panel determines what objects are shown in the other panel. This arrangement is effective for displaying and browsing information. Having two panels lets you aggregate information in areas, and the bar, or "splitter," makes it easy for users to resize the panels. + +:::image type="content" source="media/layout/splitcontainer.png" alt-text="A Windows Form with a nested split container."::: + +The image above has a split container to create a left and right pane. The right pane contains a second split container with the set to . The property is set to demonstrate the bounds of each panel. + +## Container: Tab control + +The displays multiple tabs, like dividers in a notebook or labels in a set of folders in a filing cabinet. The tabs can contain pictures and other controls. Use the tab control to produce the kind of multiple-page dialog box that appears many places in the Windows operating system, such as the Control Panel and Display Properties. Additionally, the can be used to create property pages, which are used to set a group of related properties. + +The most important property of the is , which contains the individual tabs. Each individual tab is a object. + +:::image type="content" source="media/layout/tabcontrol.png" alt-text="A Windows Form with a tab control with two tab pages."::: diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-a-picture-to-a-control/properties-image.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-a-picture-to-a-control/properties-image.png new file mode 100644 index 0000000000..56504fa8a4 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-a-picture-to-a-control/properties-image.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.gif b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.gif new file mode 100644 index 0000000000..64b1f6a1fb Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.gif differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.png new file mode 100644 index 0000000000..37d6b2ec59 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-double-click.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-drag-draw.gif b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-drag-draw.gif new file mode 100644 index 0000000000..b1c07026d1 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-add-to-a-form/toolbox-drag-draw.gif differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/double-ampersand.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/double-ampersand.png new file mode 100644 index 0000000000..c0d3006710 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/double-ampersand.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/properties-text.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/properties-text.png new file mode 100644 index 0000000000..676e40a15b Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-create-access-keys/properties-text.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/font-window.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/font-window.png new file mode 100644 index 0000000000..3df5ae4a29 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/font-window.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-font.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-font.png new file mode 100644 index 0000000000..1be544a571 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-font.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-text.png b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-text.png new file mode 100644 index 0000000000..8881c604cb Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/how-to-set-the-text-displayed-by-a-windows-forms-control/properties-text.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.gif b/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.gif new file mode 100644 index 0000000000..8c9b94915b Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.gif differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.stg b/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.stg new file mode 100644 index 0000000000..420f355442 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/anchor-resize.stg differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.pdn new file mode 100644 index 0000000000..8d5563a99a Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.png new file mode 100644 index 0000000000..12538566ce Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-left.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.pdn new file mode 100644 index 0000000000..1c8b924afc Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.png new file mode 100644 index 0000000000..9559dfd217 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-left-then-top.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.pdn new file mode 100644 index 0000000000..a39ed57442 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.png new file mode 100644 index 0000000000..7b7ef58bd4 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-modes.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.gif b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.gif new file mode 100644 index 0000000000..04b764c38b Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.gif differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.stg b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.stg new file mode 100644 index 0000000000..401729bd6d Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-resize.stg differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.pdn new file mode 100644 index 0000000000..a0f4d80c03 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.png new file mode 100644 index 0000000000..2151fd442e Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/dock-top-then-left.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/flow.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/flow.png new file mode 100644 index 0000000000..cede9600cf Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/flow.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.pdn new file mode 100644 index 0000000000..3d668f055b Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.png new file mode 100644 index 0000000000..8e8c6a3864 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/location+container.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.pdn b/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.pdn new file mode 100644 index 0000000000..d6b9f9c102 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.png new file mode 100644 index 0000000000..e10b37f109 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/panel-groupbox.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/splitcontainer.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitcontainer.png new file mode 100644 index 0000000000..34597acd1e Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitcontainer.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.gif b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.gif new file mode 100644 index 0000000000..b6e05a7db3 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.gif differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.stg b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.stg new file mode 100644 index 0000000000..36a9650361 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/splitpanel.stg differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/tabcontrol.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/tabcontrol.png new file mode 100644 index 0000000000..bf5100d2d4 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/tabcontrol.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/media/layout/table.png b/dotnet-desktop-guide/net/winforms/controls/media/layout/table.png new file mode 100644 index 0000000000..2096f230d3 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/controls/media/layout/table.png differ diff --git a/dotnet-desktop-guide/net/winforms/controls/overview.md b/dotnet-desktop-guide/net/winforms/controls/overview.md new file mode 100644 index 0000000000..926909d1b3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/overview.md @@ -0,0 +1,41 @@ +--- +title: "Overview of Using Controls" +description: Learn about how controls are used in Windows Forms for .NET. Controls are reusable components that provide functionality to the user. Many ready-to-use controls are provided. You can also make new controls. +ms.date: 10/26/2020 +ms.topic: overview +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, controls" + - "controls [Windows Forms]" + - "custom controls [Windows Forms]" +--- +# Overview of using controls (Windows Forms .NET) + +Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client-side, Windows-based applications. Not only does Windows Forms provide many ready-to-use controls, it also provides the infrastructure for developing your own controls. You can combine existing controls, extend existing controls, or author your own custom controls. For more information, see [Types of custom controls](custom.md). + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Adding controls + +Controls are added through the Visual Studio Designer. With the Designer, you can place, size, align, and move controls. Alternatively, controls can be added through code. For more information, see [Add a control (Windows Forms)](how-to-add-to-a-form.md). + +## Layout options + +The position a control appears on a parent is determined by the value of the property relative to the top-left of the parent surface. The top-left position coordinate in the parent is `(x0,y0)`. The size of the control is determined by the property and represents the width and height of the control. + +Besides manual positioning and sizing, various container controls are provided that help with automatic placement of controls. + +For more information, see [Position and layout of controls](layout.md). + + +## See also + +- [Position and layout of controls](layout.md) +- [Label control overview (Windows Forms .NET)](labels.md) +- [Add a control (Windows Forms .NET)](how-to-add-to-a-form.md) diff --git a/dotnet-desktop-guide/net/winforms/controls/provide-accessibility-information.md b/dotnet-desktop-guide/net/winforms/controls/provide-accessibility-information.md new file mode 100644 index 0000000000..9b03314147 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/provide-accessibility-information.md @@ -0,0 +1,87 @@ +--- +title: "Providing Accessibility Information for Controls on a Windows Form" +description: Learn how to add accessibility information to a control. Windows Forms lets you add accessibility settings to a control to help people with disabilities. +ms.date: 10/26/2020 +helpviewer_keywords: + - "Windows Forms controls, accessibility" + - "controls [Windows Forms], accessibility" + - "accessibility [Windows Forms], Windows Forms controls" +dev_langs: + - "csharp" + - "vb" +--- + +# Providing Accessibility Information for Controls (Windows Forms .NET) + +Accessibility aids are specialized programs and devices that help people with disabilities use computers more effectively. Examples include screen readers for people who are blind and voice input utilities for people who provide verbal commands instead of using the mouse or keyboard. These accessibility aids interact with the accessibility properties exposed by Windows Forms controls. These properties are: + +- +- +- +- +- + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## AccessibilityObject Property + +This read-only property contains an instance. The `AccessibleObject` implements the interface, which provides information about the control's description, screen location, navigational abilities, and value. The designer sets this value when the control is added to the form. + +## AccessibleDefaultActionDescription Property + +This string describes the action of the control. It does not appear in the Properties window and may only be set in code. The following example sets the property for a button control: + +```vb +Button1.AccessibleDefaultActionDescription = "Closes the application." +``` + +```csharp +button1.AccessibleDefaultActionDescription = "Closes the application."; +``` + +## AccessibleDescription Property + +This string describes the control. The property may be set in the Properties window, or in code as follows: + +```vb +Button1.AccessibleDescription = "A button with text 'Exit'." +``` + +```csharp +button1.AccessibleDescription = "A button with text 'Exit'"; +``` + +## AccessibleName Property + +This is the name of a control reported to accessibility aids. The property may be set in the Properties window, or in code as follows: + +```vb +Button1.AccessibleName = "Order" +``` + +```csharp +button1.AccessibleName = "Order"; +``` + +## AccessibleRole Property + +This property, which contains an enumeration, describes the user interface role of the control. A new control has the value set to `Default`. This would mean that by default, a `Button` control acts as a `Button`. You may want to reset this property if a control has another role. For example, you may be using a `PictureBox` control as a `Chart`, and you may want accessibility aids to report the role as a `Chart`, not as a `PictureBox`. You may also want to specify this property for custom controls you have developed. This property may be set in the Properties window, or in code as follows: + +```vb +PictureBox1.AccessibleRole = AccessibleRole.Chart +``` + +```csharp +pictureBox1.AccessibleRole = AccessibleRole.Chart; +``` + +## See also + +- [Label control overview (Windows Forms .NET)](labels.md) +- +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.Designer.cs new file mode 100644 index 0000000000..2b04413eab --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.Designer.cs @@ -0,0 +1,73 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.myUserControl = new UserControl1(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(107, 299); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // myUserControl + // + this.myUserControl.Location = new System.Drawing.Point(326, 204); + this.myUserControl.Name = "myUserControl"; + this.myUserControl.Size = new System.Drawing.Size(75, 23); + this.myUserControl.TabIndex = 0; + this.myUserControl.Text = "control"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.myUserControl); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private UserControl1 myUserControl; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.cs new file mode 100644 index 0000000000..23ed8e98ae --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + // + + // + } + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Program.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Program.cs new file mode 100644 index 0000000000..8468dcc8a3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.Designer.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.Designer.cs new file mode 100644 index 0000000000..751e300d0a --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.Designer.cs @@ -0,0 +1,37 @@ +namespace project +{ + partial class UserControl1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.cs new file mode 100644 index 0000000000..8b01713791 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class UserControl1 : UserControl + { + public UserControl1() + { + InitializeComponent(); + } + + // + protected override void OnPaint(PaintEventArgs e) + { + // Call the OnPaint method of the base class. + base.OnPaint(e); + + // Declare and instantiate a new pen that will be disposed of at the end of the method. + using var myPen = new Pen(Color.Aqua); + + // Create a rectangle that represents the size of the control, minus 1 pixel. + var area = new Rectangle(new Point(0, 0), new Size(this.Size.Width - 1, this.Size.Height - 1)); + + // Draw an aqua rectangle in the rectangle represented by the control. + e.Graphics.DrawRectangle(myPen, area); + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.resx new file mode 100644 index 0000000000..1af7de150c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/UserControl1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/project.csproj b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/project.csproj new file mode 100644 index 0000000000..dcac930ac1 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/cs/project.csproj @@ -0,0 +1,20 @@ + + + + WinExe + net5.0-windows + true + + + + + Form + + + + + UserControl + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.Designer.vb new file mode 100644 index 0000000000..972dc8b6ca --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.Designer.vb @@ -0,0 +1,61 @@ + _ +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.myUserControl = New UserControl1() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(142, 275) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'myUserControl + ' + Me.myUserControl.Location = New System.Drawing.Point(357, 188) + Me.myUserControl.Name = "myUserControl" + Me.myUserControl.Size = New System.Drawing.Size(75, 23) + Me.myUserControl.TabIndex = 0 + Me.myUserControl.Text = "Button1" + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.myUserControl) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + Friend Button1 As Windows.Forms.Button + Friend myUserControl As UserControl1 +End Class diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.vb new file mode 100644 index 0000000000..0496e1cc62 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Form1.vb @@ -0,0 +1,24 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + ' + Dim label1 As New Label With {.Text = "&First Name", + .Location = New Point(10, 10), + .TabIndex = 10} + + Dim field1 As New TextBox With {.Location = New Point(label1.Location.X, + label1.Bounds.Bottom + Padding.Top), + .TabIndex = 11} + + Controls.Add(label1) + Controls.Add(field1) + ' + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Program.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Program.vb new file mode 100644 index 0000000000..eeafc35385 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.Designer.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.Designer.vb new file mode 100644 index 0000000000..3ebf1879f0 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.Designer.vb @@ -0,0 +1,29 @@ + _ +Partial Class UserControl1 + Inherits System.Windows.Forms.UserControl + + 'UserControl overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + components = New System.ComponentModel.Container() + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + End Sub + +End Class diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.resx new file mode 100644 index 0000000000..1af7de150c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.vb new file mode 100644 index 0000000000..6370b0b868 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/UserControl1.vb @@ -0,0 +1,22 @@ +Imports System.Drawing +Imports System.Windows.Forms + +Public Class UserControl1 + + ' + Protected Overrides Sub OnPaint(e As PaintEventArgs) + MyBase.OnPaint(e) + + ' Declare and instantiate a drawing pen. + Using myPen = New System.Drawing.Pen(Color.Aqua) + + ' Create a rectangle that represents the size of the control, minus 1 pixel. + Dim area = New Rectangle(New Point(0, 0), New Size(Me.Size.Width - 1, Me.Size.Height - 1)) + + ' Draw an aqua rectangle in the rectangle represented by the control. + e.Graphics.DrawRectangle(myPen, area) + + End Using + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/projectvb.vbproj new file mode 100644 index 0000000000..811fc55337 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/custom-painting-drawing/vb/projectvb.vbproj @@ -0,0 +1,21 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + Form + + + + + UserControl + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.Designer.cs new file mode 100644 index 0000000000..e8c541b6af --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.Designer.cs @@ -0,0 +1,62 @@ +namespace cs +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(107, 299); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.cs new file mode 100644 index 0000000000..ac39542424 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace cs +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + // + Label label1 = new Label() + { + Text = "&First Name", + Location = new Point(10, 10), + TabIndex = 10 + }; + + TextBox field1 = new TextBox() + { + Location = new Point(label1.Location.X, label1.Bounds.Bottom + Padding.Top), + TabIndex = 11 + }; + + Controls.Add(label1); + Controls.Add(field1); + // + } + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Program.cs b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Program.cs new file mode 100644 index 0000000000..43fcd0a464 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace cs +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/project.csproj b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/project.csproj new file mode 100644 index 0000000000..a2d4310f05 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/cs/project.csproj @@ -0,0 +1,9 @@ + + + + WinExe + net5.0-windows + true + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.Designer.vb new file mode 100644 index 0000000000..4eae00d2de --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.Designer.vb @@ -0,0 +1,50 @@ + _ +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(354, 210) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + Friend Button1 As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.vb new file mode 100644 index 0000000000..0496e1cc62 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Form1.vb @@ -0,0 +1,24 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + ' + Dim label1 As New Label With {.Text = "&First Name", + .Location = New Point(10, 10), + .TabIndex = 10} + + Dim field1 As New TextBox With {.Location = New Point(label1.Location.X, + label1.Bounds.Bottom + Padding.Top), + .TabIndex = 11} + + Controls.Add(label1) + Controls.Add(field1) + ' + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Program.vb b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Program.vb new file mode 100644 index 0000000000..eeafc35385 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/project.vbproj b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/project.vbproj new file mode 100644 index 0000000000..b8f402e01e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/controls/snippets/how-to-add-to-a-form/vb/project.vbproj @@ -0,0 +1,10 @@ + + + + WinExe + net5.0-windows + true + project.Program + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/forms/autoscale.md b/dotnet-desktop-guide/net/winforms/forms/autoscale.md new file mode 100644 index 0000000000..82c0fb1e97 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/forms/autoscale.md @@ -0,0 +1,65 @@ +--- +title: "Automatic form scaling" +description: "A look into how Windows Forms for .NET handles scaling the UI." +ms.date: 10/26/2020 +ms.topic: overview +helpviewer_keywords: + - "scalability [Windows Forms], automatic in Windows Forms" + - "Windows Forms, automatic scaling" +--- + +# Automatic scaling (Windows Forms .NET) + +Automatic scaling enables a form and its controls, designed on one machine with a certain display resolution or font, to be displayed appropriately on another machine with a different display resolution or font. It assures that the form and its controls will intelligently resize to be consistent with native windows and other applications on both the users' and other developers' machines. Automatic scaling and visual styles enable Windows Forms applications to maintain a consistent look-and-feel when compared to native Windows applications on each user's machine. + +For the most part, automatic scaling works as expected in Windows Forms. However, font scheme changes can be problematic. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Need for automatic scaling + +Without automatic scaling, an application designed for one display resolution or font will either appear too small or too large when that resolution or font is changed. For example, if the application is designed using Tahoma 9 point as a baseline, without adjustment it will appear too small if run on a machine where the system font is Tahoma 12 point. Text elements, such as titles, menus, text box contents, and so on will render smaller than other applications. Furthermore, the size of user interface (UI) elements that contain text, such as the title bar, menus, and many controls are dependent on the font used. In this example, these elements will also appear relatively smaller. + +An analogous situation occurs when an application is designed for a certain display resolution. The most common display resolution is 96 dots per inch (DPI), which equals 100% display scaling, but higher resolution displays supporting 125%, 150%, 200% (which respectively equal 120, 144 and 192 DPI) and above are becoming more common. Without adjustment, an application, especially a graphics-based one, designed for one resolution will appear either too large or too small when run at another resolution. + +Automatic scaling seeks to address these problems by automatically resizing the form and its child controls according to the relative font size or display resolution. The Windows operating system supports automatic scaling of dialog boxes using a relative unit of measurement called dialog units. A dialog unit is based on the system font and its relationship to pixels can be determined though the Win32 SDK function `GetDialogBaseUnits`. When a user changes the theme used by Windows, all dialog boxes are automatically adjusted accordingly. In addition, Windows Forms supports automatic scaling either according to the default system font or the display resolution. Optionally, automatic scaling can be disabled in an application. + +> [!CAUTION] +> Arbitrary mixtures of DPI and font scaling modes are not supported. Although you may scale a user control using one mode (for example, DPI) and place it on a form using another mode (Font) with no issues, but mixing a base form in one mode and a derived form in another can lead to unexpected results. + +## Automatic scaling in action + +Windows Forms uses the following logic to automatically scale forms and their contents: + +01. At design time, each records the scaling mode and it current resolution in the and , respectively. + +01. At run time, the actual resolution is stored in the property. The property dynamically calculates the ratio between the run-time and design-time scaling resolution. + +01. When the form loads, if the values of and are different, then the method is called to scale the control and its children. This method suspends layout and calls the method to perform the actual scaling. Afterwards, the value of is updated to avoid progressive scaling. + +01. is also automatically invoked in the following situations: + + - In response to the event if the scaling mode is . + + - When the layout of the container control resumes and a change is detected in the or properties. + + - As implied above, when a parent is being scaled. Each container control is responsible for scaling its children using its own scaling factors and not the one from its parent container. + +01. Child controls can modify their scaling behavior through several means: + + - The property can be overridden to determine if their child controls should be scaled or not. + + - The method can be overridden to adjust the bounds that the control is scaled to, but not the scaling logic. + + - The method can be overridden to change the scaling logic for the current control. + +## See also + +- +- +- +- + + diff --git a/dotnet-desktop-guide/net/winforms/forms/events.md b/dotnet-desktop-guide/net/winforms/forms/events.md new file mode 100644 index 0000000000..b30acb2d46 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/forms/events.md @@ -0,0 +1,52 @@ +--- +title: "Events Overview" +description: "A brief overview about events with .NET Windows Forms." +ms.date: 10/26/2020 +ms.topic: overview +helpviewer_keywords: + - "Windows Forms, event handling" + - "events [Windows Forms], about events" + - "delegates [Windows Forms], multicast" + - "delegates [Windows Forms], events and" + - "multicast event delegates" + - "Windows Forms controls, events" +--- + +# Events overview (Windows Forms .NET) + +An event is an action that you can respond to, or "handle," in code. Events can be generated by a user action, such as clicking the mouse or pressing a key, by program code, or by the system. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +Event-driven applications execute code in response to an event. Each form and control exposes a predefined set of events that you can program against. If one of these events occurs and there's code an associated event handler, that code is invoked. + +The types of events raised by an object vary, but many types are common to most controls. For example, most objects will handle a event. If a user clicks a form, code in the form's event handler is executed. + +> [!NOTE] +> Many events occur in conjunction with other events. For example, in the course of the event occurring, the , , and events occur. + +For information about how to raise and consume an event, see [Handling and raising events](/dotnet/standard/events/index). + +## Delegates and their role + +Delegates are classes commonly used within .NET to build event-handling mechanisms. Delegates roughly equate to function pointers, commonly used in Visual C++ and other object-oriented languages. Unlike function pointers however, delegates are object-oriented, type-safe, and secure. Also, where a function pointer contains only a reference to a particular function, a delegate consists of a reference to an object, and references to one or more methods within the object. + +This event model uses *delegates* to bind events to the methods that are used to handle them. The delegate enables other classes to register for event notification by specifying a handler method. When the event occurs, the delegate calls the bound method. For more information about how to define delegates, see [Handling and raising events](/dotnet/standard/events/index). + +Delegates can be bound to a single method or to multiple methods, referred to as multicasting. When creating a delegate for an event, you typically create a multicast event. A rare exception might be an event that results in a specific procedure (such as displaying a dialog box) that wouldn't logically repeat multiple times per event. For information about how to create a multicast delegate, see [How to combine delegates (Multicast Delegates)](/dotnet/csharp/programming-guide/delegates/how-to-combine-delegates-multicast-delegates). + +A multicast delegate maintains an invocation list of the methods it's bound to. The multicast delegate supports a method to add a method to the invocation list and a method to remove it. + +When an event is recorded by the application, the control raises the event by invoking the delegate for that event. The delegate in turn calls the bound method. In the most common case (a multicast delegate), the delegate calls each bound method in the invocation list in turn, which provides a one-to-many notification. This strategy means that the control doesn't need to maintain a list of target objects for event notification—the delegate handles all registration and notification. + +Delegates also enable multiple events to be bound to the same method, allowing a many-to-one notification. For example, a button-click event and a menu-command–click event can both invoke the same delegate, which then calls a single method to handle these separate events the same way. + +The binding mechanism used with delegates is dynamic: a delegate can be bound at run-time to any method whose signature matches that of the event handler. With this feature, you can set up or change the bound method depending on a condition and to dynamically attach an event handler to a control. + +## See also + +- [Handling and raising events](/dotnet/standard/events/index) + + diff --git a/dotnet-desktop-guide/net/winforms/forms/how-to-add.md b/dotnet-desktop-guide/net/winforms/forms/how-to-add.md new file mode 100644 index 0000000000..82ab558f8e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/forms/how-to-add.md @@ -0,0 +1,49 @@ +--- +title: "Add a form to a project" +description: "Add a new form to a .NET Windows Forms project in Visual Studio" +ms.date: 10/26/2020 +helpviewer_keywords: + - "Windows Forms, create add form" +--- + +# How to add a form to a project (Windows Forms .NET) + +Add forms to your project with Visual Studio. When your app has multiple forms, you can choose which is the startup form for your app, and you can display multiple forms at the same time. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Add a new form + +Add a new form with Visual Studio. + +01. In Visual Studio, find the **Project Explorer** pane. Right-click on the project and choose **Add** > **Form (Windows Forms)**. + + :::image type="content" source="media/how-to-add/right-click.png" alt-text="Right click solution explorer to add new form to windows forms project"::: + +01. In the **Name** box, type a name for your form, such as *MyNewForm*. Visual Studio will provide a default and unique name that you may use. + + :::image type="content" source="media/how-to-add/new-form-dialog.png" alt-text="Add item dialog in visual studio for windows forms"::: + +Once the form has been added, Visual Studio opens the form designer for the form. + +## Add a project reference to a form + +If you have the source files to a form, you can add the form to your project by copying the files into the same folder as your project. The project automatically references any code files that are in the same folder or child folder of your project. + +Forms are made up of two files that share the same name: _form2.cs_ (_form2_ being an example of a file name) and _form2.Designer.cs_. Sometimes a resource file exists, sharing the same name, _form2.resx_. In in the previous example, _form2_ represents the base file name. You'll want to copy all related files to your project folder. + +Alternatively, you can use Visual Studio to import a file into your project. When you add an existing file to your project, the file is copied into the same folder as your project. + +01. In Visual Studio, find the **Project Explorer** pane. Right-click on the project and choose **Add** > **Existing Item**. + + :::image type="content" source="media/how-to-add/existing-right-click.png" alt-text="Right click solution explorer to add existing form to windows forms project"::: + +02. Navigate to the folder containing your form files. + +03. Select the _form2.cs_ file, where _form2_ is the base file name of the related form files. Don't select the other files, such as _form2.Designer.cs_. + +## See also + +- [How to position and size a form (Windows Forms .NET)](how-to-position-and-resize.md) +- [Events overview (Windows Forms .NET)](events.md) +- [Position and layout of controls (Windows Forms .NET)](../controls/layout.md) diff --git a/dotnet-desktop-guide/net/winforms/forms/how-to-position-and-resize.md b/dotnet-desktop-guide/net/winforms/forms/how-to-position-and-resize.md new file mode 100644 index 0000000000..2716279827 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/forms/how-to-position-and-resize.md @@ -0,0 +1,156 @@ +--- +title: "Position and resize a form" +description: "Learn how to set the size and position of a form in .NET Windows Forms and Visual Studio. The size and location can either be set in the Visual Studio designer or through code." +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "positioning Windows Forms" + - "resizing Windows Forms" + - "Windows Forms, location" + - "Windows Forms, size" +--- + +# How to position and size a form (Windows Forms .NET) + +When a form is created, the size and location is initially set to a default value. The default size of a form is generally a width and height of _800x500_ pixels. The initial location, when the form is displayed, depends on a few different settings. + +You can change the size of a form at design time with Visual Studio, and at run time with code. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Resize with the designer + +After [adding a new form](how-to-add.md) to the project, the size of a form is set in two different ways. First, you can set it is with the size grips in the designer. By dragging either the right edge, bottom edge, or the corner, you can resize the form. + +:::image type="content" source="media/how-to-position-and-resize/designer-grips.png" alt-text="Right click solution explorer to add new form to windows forms project with grips"::: + +The second way you can resize the form while the designer is open, is through the properties pane. Select the form, then find the **Properties** pane in Visual Studio. Scroll down to **size** and expand it. You can set the **Width** and **Height** manually. + +:::image type="content" source="media/how-to-position-and-resize/designer-properties-size.png" alt-text="Right click solution explorer to add new form to windows forms project"::: + +## Resize in code + +Even though the designer sets the starting size of a form, you can resize it through code. Using code to resize a form is useful when something about your application determines that the default size of the form is insufficient. + +To resize a form, change the , which represents the width and height of the form. + +### Resize the current form + +You can change the size of the current form as long as the code is running within the context of the form. For example, if you have `Form1` with a button on it, that when clicked invokes the `Click` event handler to resize the form: + +```csharp +private void button1_Click(object sender, EventArgs e) => + Size = new Size(250, 200); +``` + +```vb +Private Sub Button1_Click(sender As Object, e As EventArgs) + Size = New Drawing.Size(250, 200) +End Sub +``` + +### Resize a different form + +You can change the size of another form after it's created by using the variable referencing the form. For example, let's say you have two forms, `Form1` (the startup form in this example) and `Form2`. `Form1` has a button that when clicked, invokes the `Click` event. The handler of this event creates a new instance of the `Form2` form, sets the size, and then displays it: + +```csharp +private void button1_Click(object sender, EventArgs e) +{ + Form2 form = new Form2(); + form.Size = new Size(250, 200); + form.Show(); +} +``` + +```vb +Private Sub Button1_Click(sender As Object, e As EventArgs) + Dim form = New Form2 With { + .Size = New Drawing.Size(250, 200) + } + form.Show() +End Sub +``` + +If the `Size` isn't manually set, the form's default size is what it was set to during design-time. + +## Position with the designer + +When a form instance is created and displayed, the initial location of the form is determined by the property. The property holds the current location the form. Both properties can be set through the designer. + +:::image type="content" source="media/how-to-position-and-resize/startposition.png" alt-text="visual studio properties pane with start position highlighted"::: + +| FormStartPosition Enum | Description | +|------------------------|------------------------------------------------------------------------------------------------------------------| +| CenterParent | The form is centered within the bounds of its parent form. | +| CenterScreen | The form is centered on the current display. | +| Manual | The position of the form is determined by the [Location](xref:System.Windows.Forms.Form.Location%2A) property. | +| WindowsDefaultBounds | The form is positioned at the Windows default location and is resized to the default size determined by Windows. | +| WindowsDefaultLocation | The form is positioned at the Windows default location and isn't resized. | + +The [CenterParent](xref:System.Windows.Forms.FormStartPosition.CenterParent) value only works with forms that are either a multiple document interface (MDI) child form, or a normal form that is displayed with the method. `CenterParent` has no affect on a normal form that is displayed with the method. To center a form (`form` variable) to another form (`parentForm` variable), use the following code: + +```csharp +form.StartPosition = FormStartPosition.Manual; +form.Location = new Point(parentForm.Width / 2 - form.Width / 2 + parentForm.Location.X, + parentForm.Height / 2 - form.Height / 2 + parentForm.Location.Y); +form.Show(); +``` + +```vb +form.StartPosition = Windows.Forms.FormStartPosition.CenterParent.Manual +form.Location = New Drawing.Point(parentForm.Width / 2 - form.Width / 2 + parentForm.Location.X, + parentForm.Height / 2 - form.Height / 2 + parentForm.Location.Y) + +form.Show() +``` + +## Position with code + +Even though the designer can be used to set the starting location of a form, you can use code either change the starting position mode or set the location manually. Using code to position a form is useful if you need to manually position and size a form in relation to the screen or other forms. + +### Move the current form + +You can move the current form as long as the code is running within the context of the form. For example, if you have `Form1` with a button on it, that when clicked invokes the `Click` event handler. The handler in this example changes the location of the form to the top-left of the screen by setting the property: + +```csharp +private void button1_Click(object sender, EventArgs e) => + Location = new Point(0, 0); +``` + +```vb +Private Sub Button1_Click(sender As Object, e As EventArgs) + Location = New Drawing.Point(0, 0) +End Sub +``` + +### Position a different form + +You can change the location of another form after it's created by using the variable referencing the form. For example, let's say you have two forms, `Form1` (the startup form in this example) and `Form2`. `Form1` has a button that when clicked, invokes the `Click` event. The handler of this event creates a new instance of the `Form2` form and sets the size: + +```csharp +private void button1_Click(object sender, EventArgs e) +{ + Form2 form = new Form2(); + form.Size = new Size(250, 200); + form.Show(); +} +``` + +```vb +Private Sub Button1_Click(sender As Object, e As EventArgs) + Dim form = New Form2 With { + .Size = New Drawing.Size(250, 200) + } + form.Show() +End Sub +``` + +If the `Size` isn't set, the form's default size is what it was set to at design-time. + +## See also + +- [How to add a form to a project (Windows Forms .NET)](how-to-add.md) +- [Events overview (Windows Forms .NET)](events.md) +- [Position and layout of controls (Windows Forms .NET)](../controls/layout.md) diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.pdn b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.pdn new file mode 100644 index 0000000000..b7ae8fde9c Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.png new file mode 100644 index 0000000000..b690062f5d Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/existing-right-click.png differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/new-form-dialog.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/new-form-dialog.png new file mode 100644 index 0000000000..e7068f6752 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/new-form-dialog.png differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.pdn b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.pdn new file mode 100644 index 0000000000..42cbae2f5a Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.png new file mode 100644 index 0000000000..d672b4a4a4 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-add/right-click.png differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-grips.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-grips.png new file mode 100644 index 0000000000..debda9d3db Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-grips.png differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-properties-size.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-properties-size.png new file mode 100644 index 0000000000..3f6a9e3873 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/designer-properties-size.png differ diff --git a/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/startposition.png b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/startposition.png new file mode 100644 index 0000000000..c37019a7a7 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/forms/media/how-to-position-and-resize/startposition.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/create-app-visual-studio.md b/dotnet-desktop-guide/net/winforms/get-started/create-app-visual-studio.md new file mode 100644 index 0000000000..54c67b312f --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/create-app-visual-studio.md @@ -0,0 +1,163 @@ +--- +title: "Create a new app with Visual Studio tutorial" +description: Follow this tutorial to learn how to create a new Windows Forms app for .NET with Visual Studio 2019. +ms.date: 10/26/2020 +ms.topic: tutorial +dev_langs: + - "csharp" + - "vb" +--- + +# Tutorial: Create a new WinForms app (Windows Forms .NET) + +In this short tutorial, you'll learn how to create a new Windows Forms (WinForms) app with Visual Studio. Once the initial app has been generated, you'll learn how to add controls and how to handle events. By the end of this tutorial, you'll have a simple app that adds names to a list box. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +In this tutorial, you learn how to: + +> [!div class="checklist"] +> +> - Create a new WinForms app +> - Add controls to a form +> - Handle control events to provide app functionality +> - Run the app + +## Prerequisites + +- [Visual Studio 2019 version 16.8 Preview](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms) +- [Visual Studio Desktop workload](/visualstudio/install/modify-visual-studio?view=vs-2019&preserve-view=true) + +## Create a WinForms app + +The first step to creating a new app is opening Visual Studio and generating the app from a template. + +01. Open Visual Studio. +01. Select **Create a new project**. + + :::image type="content" source="media/create-app-visual-studio/vs-create-new-project.png" alt-text="Create a new Windows Forms project in Visual Studio 2019 for .NET"::: + +01. In the **Search for templates** box, type **winforms**, and then press Enter. +01. In the **code language** dropdown, choose **C#** or **Visual Basic**. +01. In the templates list, select **Windows Forms App (.NET)** and then click **Next**. + + > [!IMPORTANT] + > Don't select the **Windows Forms App (.NET _Framework_)** template. + + :::image type="content" source="media/create-app-visual-studio/vs-template-search.png" alt-text="Search for the Windows Forms template in Visual Studio 2019 for .NET"::: + +01. In the **Configure your new project** window, set the **Project name** to **Names** and click **Create**. + + You can also save your project to a different folder by adjusting the **Location** setting. + + :::image type="content" source="media/create-app-visual-studio/vs-config-new-project.png" alt-text="Configure new Windows Forms project in Visual Studio 2019 for .NET"::: + +Once the app is generated, Visual Studio should open the designer pane for the default form, _Form1_. If the form designer isn't visible, double-click on the form in the **Solution Explorer** pane to open the designer window. + +### Important parts of Visual Studio + +Support for WinForms in Visual Studio has four important components that you'll interact with as you create an app: + +:::image type="content" source="media/create-app-visual-studio/vs-main-window.png" alt-text="The important components of Visual Studio you should know when creating a Windows Forms project for .NET"::: + +01. Solution Explorer + + All if your project files, code, forms, resources, will appear in this pane. + +02. Properties + + This pane shows property settings you can configure based on the item selected. For example, if you select an item from **Solution Explorer**, you'll see property settings related to the file. If you select an object in the **Designer**, you'll see settings for the control or form. + +03. Form Designer + + This is the designer for the form. It's interactive and you can drag-and-drop objects from the **Toolbox**. By selecting and moving items in the designer, you can visually compose the user interface (UI) for your app. + +04. Toolbox + + The toolbox contains all of the controls you can add to a form. To add a control to the current form, double-click a control or drag-and-drop the control. + +## Add controls to the form + +With the _Form1_ form designer open, use the **Toolbox** pane to add the following controls to the form: + +- Label +- Button +- Listbox +- Textbox + +You can position and size the controls according to the following settings. Either visually move them to match the screenshot that follows, or click on each control and configure the settings in the **Properties** pane. You can also click on the form title area to select the form: + +| Object | Setting | Value | +|---------|----------|------------| +| Form | Text | `Names` | +| | Size | `268, 180` | +| Label | Location | `12, 9` | +| | Text | `Names` | +| Listbox | Name | `lstNames` | +| | Location | `12, 27` | +| | Size | `120, 94` | +| Textbox | Name | `txtName` | +| | Location | `138, 26` | +| | Size | `100, 23` | +| Button | Name | `btnAdd` | +| | Location | `138, 55` | +| | Size | `100, 23` | +| | Text | `Add Name` | + +You should have a form in the designer that looks similar to the following: + +:::image type="content" source="media/create-app-visual-studio/vs-form-preview.png" alt-text="Visual Studio 2019 designer with the form open for Windows Forms for .NET"::: + +## Handle events + +Now that the form has all of its controls laid out, you need to handle the events of the controls to respond to user input. With the form designer still open, perform the following steps: + +01. Select the button control on the form. +01. In the **Properties** pane, click on the events icon :::image type="icon" source="media/create-app-visual-studio/icon-events.png" border="false"::: to list the events of the button. +01. Find the **Click** event and double-click it to generate an event handler. + + This action adds the following code to the the form: + + ```csharp + private void btnAdd_Click(object sender, EventArgs e) + { + + } + ``` + + ```vb + Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click + + End Sub + ``` + + The code we'll put in this handler will add the name specified by the `txtName` textbox control to the `lstNames` listbox control. However, we want there to be two conditions to adding the name: the name provided must not be blank, and the name must not already exist. + +01. The following code demonstrates adding a name to the `lstNames` control: + + ```csharp + private void btnAdd_Click(object sender, EventArgs e) + { + if (!string.IsNullOrWhiteSpace(txtName.Text) && !lstNames.Items.Contains(txtName.Text)) + lstNames.Items.Add(txtName.Text); + } + ``` + + ```vb + Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click + If Not String.IsNullOrWhiteSpace(txtName.Text) And Not lstNames.Items.Contains(txtName.Text) Then + lstNames.Items.Add(txtName.Text) + End If + End Sub + ``` + +## Run the app + +Now that the event has been coded, you can run the app by pressing the F5 key or by selecting **Debug** > **Start Debugging** from the menu. The form displays and you can enter a name in the textbox and then add it by clicking the button. + +:::image type="content" source="media/create-app-visual-studio/app-running.png" alt-text="Running a Windows Forms for .NET app."::: + +## Next steps + +> [!div class="nextstepaction"] +> [Learn more about Windows Forms](../overview/index.md) diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/app-running.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/app-running.png new file mode 100644 index 0000000000..5601d7e001 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/app-running.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-events.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-events.png new file mode 100644 index 0000000000..6788a1b83c Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-events.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-properties.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-properties.png new file mode 100644 index 0000000000..036f23db3e Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/icon-properties.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-config-new-project.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-config-new-project.png new file mode 100644 index 0000000000..729f5605b3 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-config-new-project.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-create-new-project.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-create-new-project.png new file mode 100644 index 0000000000..1e41598f87 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-create-new-project.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-form-preview.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-form-preview.png new file mode 100644 index 0000000000..3a98f799e8 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-form-preview.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.pdn b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.pdn new file mode 100644 index 0000000000..1f94bd1362 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.pdn differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.png new file mode 100644 index 0000000000..c6644006e8 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-main-window.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-properties-events.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-properties-events.png new file mode 100644 index 0000000000..450c8b4406 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-properties-events.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-solution-explorer-form.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-solution-explorer-form.png new file mode 100644 index 0000000000..17524fbaf1 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-solution-explorer-form.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-cs.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-cs.png new file mode 100644 index 0000000000..c0fab7cde7 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-cs.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-vb.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-vb.png new file mode 100644 index 0000000000..47a40cf45f Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search-vb.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search.png b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search.png new file mode 100644 index 0000000000..62ccd683c0 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/get-started/media/create-app-visual-studio/vs-template-search.png differ diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.Designer.cs b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.Designer.cs new file mode 100644 index 0000000000..8dce82c2d7 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.Designer.cs @@ -0,0 +1,98 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.label1 = new System.Windows.Forms.Label(); + this.lstNames = new System.Windows.Forms.ListBox(); + this.btnAdd = new System.Windows.Forms.Button(); + this.txtName = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 9); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(44, 15); + this.label1.TabIndex = 0; + this.label1.Text = "Names"; + // + // lstNames + // + this.lstNames.FormattingEnabled = true; + this.lstNames.ItemHeight = 15; + this.lstNames.Location = new System.Drawing.Point(12, 27); + this.lstNames.Name = "lstNames"; + this.lstNames.Size = new System.Drawing.Size(120, 94); + this.lstNames.TabIndex = 1; + // + // btnAdd + // + this.btnAdd.Location = new System.Drawing.Point(138, 55); + this.btnAdd.Name = "btnAdd"; + this.btnAdd.Size = new System.Drawing.Size(100, 23); + this.btnAdd.TabIndex = 2; + this.btnAdd.Text = "Add Name"; + this.btnAdd.UseVisualStyleBackColor = true; + this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); + // + // txtName + // + this.txtName.Location = new System.Drawing.Point(138, 26); + this.txtName.Name = "txtName"; + this.txtName.Size = new System.Drawing.Size(100, 23); + this.txtName.TabIndex = 3; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(252, 141); + this.Controls.Add(this.txtName); + this.Controls.Add(this.btnAdd); + this.Controls.Add(this.lstNames); + this.Controls.Add(this.label1); + this.Cursor = System.Windows.Forms.Cursors.Default; + this.Name = "Form1"; + this.Text = "Names"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.ListBox lstNames; + private System.Windows.Forms.Button btnAdd; + private System.Windows.Forms.TextBox txtName; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.cs b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.cs new file mode 100644 index 0000000000..9b22c60906 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + + } + + private void btnAdd_Click(object sender, EventArgs e) + { + if (!string.IsNullOrWhiteSpace(txtName.Text) && !lstNames.Items.Contains(txtName.Text)) + lstNames.Items.Add(txtName.Text); + } + + } +} diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.resx b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Main.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Program.cs new file mode 100644 index 0000000000..07516585b7 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/project.csproj new file mode 100644 index 0000000000..aa90722ac3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/csharp/project.csproj @@ -0,0 +1,13 @@ + + + + WinExe + net5.0-windows + true + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.Designer.vb b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.Designer.vb new file mode 100644 index 0000000000..cf8dde7d5f --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.Designer.vb @@ -0,0 +1,85 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Label1 = New System.Windows.Forms.Label() + Me.lstNames = New System.Windows.Forms.ListBox() + Me.txtName = New System.Windows.Forms.TextBox() + Me.btnAdd = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Label1 + ' + Me.Label1.AutoSize = True + Me.Label1.Location = New System.Drawing.Point(12, 9) + Me.Label1.Name = "Label1" + Me.Label1.Size = New System.Drawing.Size(44, 15) + Me.Label1.TabIndex = 0 + Me.Label1.Text = "Names" + ' + 'lstNames + ' + Me.lstNames.FormattingEnabled = True + Me.lstNames.ItemHeight = 15 + Me.lstNames.Location = New System.Drawing.Point(12, 27) + Me.lstNames.Name = "lstNames" + Me.lstNames.Size = New System.Drawing.Size(120, 94) + Me.lstNames.TabIndex = 1 + ' + 'txtName + ' + Me.txtName.Location = New System.Drawing.Point(138, 26) + Me.txtName.Name = "txtName" + Me.txtName.Size = New System.Drawing.Size(100, 23) + Me.txtName.TabIndex = 2 + ' + 'btnAdd + ' + Me.btnAdd.Location = New System.Drawing.Point(138, 55) + Me.btnAdd.Name = "btnAdd" + Me.btnAdd.Size = New System.Drawing.Size(100, 23) + Me.btnAdd.TabIndex = 3 + Me.btnAdd.Text = "Add Name" + Me.btnAdd.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(252, 141) + Me.Controls.Add(Me.btnAdd) + Me.Controls.Add(Me.txtName) + Me.Controls.Add(Me.lstNames) + Me.Controls.Add(Me.Label1) + Me.Name = "Form1" + Me.Text = "Names" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend WithEvents Label1 As Windows.Forms.Label + Friend WithEvents lstNames As Windows.Forms.ListBox + Friend WithEvents txtName As Windows.Forms.TextBox + Friend WithEvents btnAdd As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.resx b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.vb b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.vb new file mode 100644 index 0000000000..bef5f98437 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Main.vb @@ -0,0 +1,19 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load + + End Sub + + Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click + If Not String.IsNullOrWhiteSpace(txtName.Text) And Not lstNames.Items.Contains(txtName.Text) Then + lstNames.Items.Add(txtName.Text) + End If + End Sub +End Class diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Program.vb b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Program.vb new file mode 100644 index 0000000000..3551285240 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/projectvb.vbproj new file mode 100644 index 0000000000..38f543443c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/get-started/snippets/create-app-visual-studio/vb/projectvb.vbproj @@ -0,0 +1,14 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/index.md b/dotnet-desktop-guide/net/winforms/index.md deleted file mode 100644 index 7cfc6cd556..0000000000 --- a/dotnet-desktop-guide/net/winforms/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Windows Forms -titleSuffix: ".NET" -description: Learn what it takes to get started with Windows Forms and how to enhance your Windows Forms applications. -ms.date: "08/30/2020" -helpviewer_keywords: - - "Windows Forms" - - "user interface" - - "user interface [Windows Forms], forms" - - ".NET 5" ---- - -# Windows Forms for .NET 5 and .NET Core 3.1 - -Welcome to the Desktop Guide for Windows Forms, a UI framework that creates rich desktop client apps for Windows. The Windows Forms development platform supports a broad set of app development features, including controls, graphics, data binding, and user input. Windows Forms features a drag-and-drop visual designer in Visual Studio to easily create Windows Forms apps. - -[!INCLUDE [desktop guide under construction](../includes/desktop-guide-preview-note.md)] - -There are two implementations of Windows Forms: - -01. The open-source implementation hosted on [GitHub](https://github.com/dotnet/winforms). - - This version runs on .NET 5 and .NET Core 3.1. The Windows Forms Visual Designer requires, at a minimum, [Visual Studio 2019 version 16.X](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms). - - Even though this version of .NET is cross-platform, Windows Forms remains a Windows-only technology. - -01. The [.NET Framework 4 implementation](../../framework/winforms/index.yml?view=netframeworkdesktop-4.8) that's supported by Visual Studio 2019 and Visual Studio 2017. - - .NET Framework 4 is a Windows-only version of .NET and is considered a Windows Operating System component. This version of Windows Forms is distributed with .NET Framework. - -This guide is written for Windows Forms on .NET 5 (and .NET Core 3.1) and later versions. For more information about the .NET Framework version of Windows Forms, see [Windows Forms for .NET Framework](../../framework/winforms/index.yml?view=netframeworkdesktop-4.8). diff --git a/dotnet-desktop-guide/net/winforms/index.yml b/dotnet-desktop-guide/net/winforms/index.yml new file mode 100644 index 0000000000..453ee086cd --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/index.yml @@ -0,0 +1,83 @@ +### YamlMime:Landing + +title: Windows Forms documentation +summary: Learn about using Windows Forms, an open-source, graphical user interface for Windows, on .NET 5. + +metadata: + title: Windows Forms for .NET 5 documentation + description: Learn about using Windows Forms, an open-source, graphical user interface for Windows, on .NET 5. + ms.topic: landing-page + ms.date: 10/26/2020 + +# linkListType: architecture | concept | deploy | download | get-started | how-to-guide | learn | overview | quickstart | reference | sample | tutorial | video | whats-new + +landingContent: + + # Card + - title: Learn about Windows Forms + linkLists: + - linkListType: download + links: + - text: Visual Studio 2019 version 16.8 Preview + url: https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms + - linkListType: overview + links: + - text: Windows Forms overview + url: overview/index.md + - linkListType: tutorial + links: + - text: Create a new app + url: get-started/create-app-visual-studio.md + + - title: Controls + linkLists: + - linkListType: overview + links: + - text: About controls + url: controls/overview.md + - linkListType: concept + links: + - text: Layout + url: controls/layout.md + - linkListType: how-to-guide + links: + - text: Add a control + url: controls/how-to-add-to-a-form.md + - text: Add access (shortcut) keys + url: controls/how-to-create-access-keys.md + + - title: Keyboard input + linkLists: + - linkListType: overview + links: + - text: About the keyboard + url: input-keyboard/overview.md + - linkListType: concept + links: + - text: Keyboard events + url: input-keyboard/events.md + - linkListType: how-to-guide + links: + - text: Handle keyboard input + url: input-keyboard/how-to-handle-forms.md + - text: Modify key events + url: input-keyboard/how-to-change-key-press.md + + - title: Mouse input + linkLists: + - linkListType: overview + links: + - text: About the mouse + url: input-mouse/overview.md + - linkListType: concept + links: + - text: Mouse events + url: input-mouse/events.md + - text: Drag-and-drop + url: input-mouse/drag-and-drop.md + - linkListType: how-to-guide + links: + - text: Manage the cursor + url: input-mouse/how-to-manage-cursor-pointer.md + - text: Simulate mouse events + url: input-mouse/how-to-simulate-events.md diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/events.md b/dotnet-desktop-guide/net/winforms/input-keyboard/events.md new file mode 100644 index 0000000000..65573a4d34 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/events.md @@ -0,0 +1,47 @@ +--- +title: "Using keyboard events" +description: Overview of using keyboard events to handle keyboard input. This article provides a list of keyboard-related events and when to use them. +ms.date: 10/26/2020 +ms.topic: overview +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "KeyPress event [Windows Forms]" + - "keyboards [Windows Forms], keyboard events" + - "KeyUp event" + - "KeyDown event" + - "keyboard events" + - "events [Windows Forms], keyboard" +--- +# Using keyboard events (Windows Forms .NET) + +Most Windows Forms programs process keyboard input by handling the keyboard events. This article provides an overview of the keyboard events, including details on when to use each event and the data that is supplied for each event. For more information about events in general, see [Events overview (Windows Forms .NET)](../forms/events.md). + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Keyboard events + +Windows Forms provides two events that occur when a user presses a keyboard key and one event when a user releases a keyboard key: + +- The event occurs once. +- The event, which can occur multiple times when a user holds down the same key. +- The event occurs once when a user releases a key. + +When a user presses a key, Windows Forms determines which event to raise based on whether the keyboard message specifies a character key or a physical key. For more information about character and physical keys, see [Keyboard overview, keyboard events](overview.md#keyboard-events). + +The following table describes the three keyboard events. + +|Keyboard event|Description|Results| +|--------------------|-----------------|-------------| +||This event is raised when a user presses a physical key.|The handler for receives:

  • A parameter, which provides the property (which specifies a physical keyboard button).
  • The property (SHIFT, CTRL, or ALT).
  • The property (which combines the key code and modifier). The parameter also provides:

    • The property, which can be set to prevent the underlying control from receiving the key.
    • The property, which can be used to suppress the and events for that keystroke.
| +||This event is raised when the key or keys pressed result in a character. For example, a user presses SHIFT and the lowercase "a" keys, which result in a capital letter "A" character.| is raised after .

  • The handler for receives:
  • A parameter, which contains the character code of the key that was pressed. This character code is unique for every combination of a character key and a modifier key.

    For example, the "A" key will generate:

    • The character code 65, if it is pressed with the SHIFT key
    • Or the CAPS LOCK key, 97 if it is pressed by itself,
    • And 1, if it is pressed with the CTRL key.
| +||This event is raised when a user releases a physical key.|The handler for receives:

  • A parameter:

    • Which provides the property (which specifies a physical keyboard button).
    • The property (SHIFT, CTRL, or ALT).
    • The property (which combines the key code and modifier).
| + +## See also + +- [Overview of using the keyboard (Windows Forms .NET)](overview.md) +- [How to modify keyboard key events (Windows Forms .NET)](how-to-change-key-press.md) +- [How to Check for modifier key presses (Windows Forms .NET)](how-to-check-modifier-key.md) +- [How to simulate keyboard events (Windows Forms .NET)](how-to-simulate-events.md) +- [How to handle keyboard input messages in the form (Windows Forms .NET)](how-to-handle-forms.md) diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-change-key-press.md b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-change-key-press.md new file mode 100644 index 0000000000..be1cb6bc8b --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-change-key-press.md @@ -0,0 +1,60 @@ +--- +title: "Modify keyboard key events" +description: Learn how to intercept a key press and modify which key is pressed on a Windows Forms .NET application. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyboard input [Windows Forms], modifying" + - "modifying keyboard input" + - "Windows Forms, modifying keyboard input" + - "keyboards [Windows Forms], keyboard input" +--- +# How to modify keyboard key events (Windows Forms .NET) + +Windows Forms provides the ability to consume and modify keyboard input. Consuming a key refers to handling a key within a method or event handler so that other methods and events further down the message queue don't receive the key value. And, modifying a key refers to modifying the value of a key so that methods and event handlers further down the message queue receive a different key value. This article shows how to accomplish these tasks. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Consume a key + +In a event handler, set the property of the class to `true`. + +-or- + +In a event handler, set the property of the class to `true`. + +> [!NOTE] +> Setting the property in the event handler does not prevent the and events from being raised for the current keystroke. Use the property for this purpose. + +The following example handles the event to consume the `A` and `a` character keys. Those keys can't be typed into the text box: + +:::code language="csharp" source="snippets/how-to-change-key-press/csharp/Form1.cs" id="ConsumeKey"::: +:::code language="vb" source="snippets/how-to-change-key-press/vb/Form1.vb" id="ConsumeKey"::: + +## Modify a standard character key + +In a event handler, set the property of the class to the value of the new character key. + +The following example handles the event to change any `A` and `a` character keys to `!`: + +:::code language="csharp" source="snippets/how-to-change-key-press/csharp/Form1.cs" id="ModifyKey"::: +:::code language="vb" source="snippets/how-to-change-key-press/vb/Form1.vb" id="ModifyKey"::: + +## Modify a non-character key + +You can only modify non-character key presses by inheriting from the control and overriding the method. As the input is sent to the control, it's processed before the control raising events. You can intercept these messages to modify or block them. + +The following code example demonstrates how to use the property of the parameter to change the key pressed. This code detects a key from F1 through F10 and translates the key into a numeric key ranging from 0 through 9 (where F10 maps to 0). + +:::code language="csharp" source="snippets/how-to-change-key-press/csharp/NewTextBox.cs" id="PreProcessMessage"::: +:::code language="vb" source="snippets/how-to-change-key-press/vb/NewTextBox.vb" id="PreProcessMessage"::: + +## See also + +- [Overview of using the keyboard (Windows Forms .NET)](overview.md) +- [Using keyboard events (Windows Forms .NET)](events.md) +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-check-modifier-key.md b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-check-modifier-key.md new file mode 100644 index 0000000000..42bf5ccc83 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-check-modifier-key.md @@ -0,0 +1,62 @@ +--- +title: "Check which modifier key is pressed" +description: Learn how to detect when the SHIFT, ALT, or CTRL keys are pressed in Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyboard input" + - "shift keys" + - "events [Windows Forms], mouse" + - "Keys.ControlKey enumeration member" + - "keys [Windows Forms], control keys" + - "user input [Windows Forms], checking for keyboard" + - "keys [Windows Forms], determining last pressed" + - "keys [Windows Forms], shift keys" + - "keys [Windows Forms], modifier keys" + - "control keys" + - "keys [Windows Forms], alt keys" + - "alt keys" + - "Keys.Shift enumeration member" + - "events [Windows Forms], keyboard" + - "keyboards [Windows Forms], keyboard input" + - "Keys.Alt enumeration member" + - "modifier keys" +--- +# How to check for modifier key presses (Windows Forms .NET) + +As the user types keys into your application, you can monitor for pressed modifier keys such as the SHIFT, ALT, and CTRL. When a modifier key is pressed in combination with other keys or even a mouse click, your application can respond appropriately. For example, pressing the S key may cause an "s" to appear on the screen. If the keys CTRL+S are pressed, instead, the current document may be saved. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +If you handle the event, the property received by the event handler specifies which modifier keys are pressed. Also, the property specifies the character that was pressed along with any modifier keys combined with a bitwise OR. + +If you're handling the event or a mouse event, the event handler doesn't receive this information. Use the property of the class to detect a key modifier. In either case, you must perform a bitwise AND of the appropriate value and the value you're testing. The enumeration offers variations of each modifier key, so it's important that you do the bitwise AND check with the correct value. + +For example, the SHIFT key is represented by the following key values: + +- +- +- +- + +The correct value to test SHIFT as a modifier key is . Similarly, to test for CTRL and ALT as modifiers you should use the and values, respectively. + +## Detect modifier key + +Detect if a modifier key is pressed by comparing the property and the enumeration value with a bitwise AND operator. + +The following code example shows how to determine whether the SHIFT key is pressed within the and event handlers. + +:::code language="csharp" source="snippets/how-to-check-modifier-key/csharp/Form1.cs" id="DetectModifier"::: +:::code language="vb" source="snippets/how-to-check-modifier-key/vb/Form1.vb" id="DetectModifier"::: + +## See also + +- [Overview of using the keyboard (Windows Forms .NET)](overview.md) +- [Using keyboard events (Windows Forms .NET)](events.md) +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-handle-forms.md b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-handle-forms.md new file mode 100644 index 0000000000..03d0d5373b --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-handle-forms.md @@ -0,0 +1,34 @@ +--- +title: "Handle keyboard input at the Form level" +description: Learn how to handle keyboard input for your Windows Forms at the form level, before messages reach a control. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyboard input [Windows Forms], at form level" + - "Windows Forms, handling keyboard input" + - "keyboards [Windows Forms], form-level input" +--- + +# How to handle keyboard input messages in the form (Windows Forms .NET) + +Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control. This article shows how to accomplish this task. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Handle a keyboard message + +Handle the or event of the active form and set the property of the form to `true`. This property causes the keyboard to be received by the form before they reach any controls on the form. The following code example handles the event by detecting all of the number keys and consuming 1, 4, and 7. + +:::code language="csharp" source="snippets/how-to-handle-forms/csharp/Form1.cs" id="HandleKey"::: +:::code language="vb" source="snippets/how-to-handle-forms/vb/Form1.vb" id="HandleKey"::: + +## See also + +- [Overview of using the keyboard (Windows Forms .NET)](overview.md) +- [Using keyboard events (Windows Forms .NET)](events.md) +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-simulate-events.md b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-simulate-events.md new file mode 100644 index 0000000000..e95db66179 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/how-to-simulate-events.md @@ -0,0 +1,77 @@ +--- +title: "Simulate keyboard events" +description: Learn how to simulate keyboard events in Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyboards [Windows Forms], event simulation" + - "user input [Windows Forms], simulating" + - "SendKeys [Windows Forms], using" +--- +# How to simulate keyboard events (Windows Forms .NET) + +Windows Forms provides a few options for programmatically simulating keyboard input. This article provides an overview of these options. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Use SendKeys + +Windows Forms provides the class for sending keystrokes to the active application. There are two methods to send keystrokes to an application: and . The difference between the two methods is that `SendWait` blocks the current thread when the keystroke is sent, waiting for a response, while `Send` doesn't. For more information about `SendWait`, see [To send a keystroke to a different application](#to-send-a-keystroke-to-a-different-application). + +> [!CAUTION] +> If your application is intended for international use with a variety of keyboards, the use of could yield unpredictable results and should be avoided. + +Behind the scenes, `SendKeys` uses an older Windows implementation for sending input, which may fail on modern Windows where it's expected that the application isn't running with administrative rights. If the older implementation fails, the code automatically tries the newer Windows implementation for sending input. Additionally, when the class uses the new implementation, the method no longer blocks the current thread when sending keystrokes to another application. + +> [!IMPORTANT] +> If your application relies on consistent behavior regardless of the operating system, you can force the class to use the new implementation by adding the following application setting to your app.config file. +> +> ```xml +> +> +> +> ``` +> +> To force the class to _only_ use the previous implementation, use the value `"JournalHook"` instead. + +### To send a keystroke to the same application + +Call the or method of the class. The specified keystrokes will be received by the active control of the application. + +The following code example uses `Send` to simulate pressing the ALT and DOWN keys together. These keystrokes cause the control to display its dropdown. This example assumes a with a and . + +:::code language="csharp" source="snippets/how-to-simulate-events/csharp/Form1.cs" id="ShowDropDown"::: +:::code language="vb" source="snippets/how-to-simulate-events/vb/Form1.vb" id="ShowDropDown"::: + +### To send a keystroke to a different application + +The and methods send keystrokes to the active application, which is usually the application you're sending keystrokes from. To send keystrokes to another application, you first need to activate it. Because there's no managed method to activate another application, you must use native Windows methods to focus the other application. The following code example uses platform invoke to call the `FindWindow` and `SetForegroundWindow` methods to activate the Calculator application window, and then calls `Send` to issue a series of calculations to the Calculator application. + +The following code example uses `Send` to simulate pressing keys into the Windows 10 Calculator application. It first searches for an application window with title of `Calculator` and then activates it. Once activated, the keystrokes are sent to calculate 10 plus 10. + +:::code language="csharp" source="snippets/how-to-simulate-events/csharp/Form2.cs" id="Calculator"::: +:::code language="vb" source="snippets/how-to-simulate-events/vb/Form2.vb" id="Calculator"::: + +## Use OnEventName methods + +The easiest way to simulate keyboard events is to call a method on the object that raises the event. Most events have a corresponding method that invokes them, named in the pattern of `On` followed by `EventName`, such as `OnKeyPress`. This option is only possible within custom controls or forms, because these methods are protected and can't be accessed from outside the context of the control or form. + +These protected methods are available to simulate keyboard events. + +- `OnKeyDown` +- `OnKeyPress` +- `OnKeyUp` + +For more information about these events, see [Using keyboard events (Windows Forms .NET)](events.md). + +## See also + +- [Overview of using the keyboard (Windows Forms .NET)](overview.md) +- [Using keyboard events (Windows Forms .NET)](events.md) +- [Using mouse events (Windows Forms .NET)](../input-mouse/events.md) +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/overview.md b/dotnet-desktop-guide/net/winforms/input-keyboard/overview.md new file mode 100644 index 0000000000..d2ec35b488 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/overview.md @@ -0,0 +1,102 @@ +--- +title: "Overview of keyboard input" +description: Learn about how keyboard input works in Windows Forms for .NET. Keyboard events are raised by forms and controls and represent keys that are down, pressed, or up. +ms.date: 10/26/2020 +ms.topic: overview +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, keyboard input" + - "keyboard [Windows Forms], input" +--- + +# Overview of using the keyboard (Windows Forms .NET) + +In Windows Forms, user input is sent to applications in the form of [Windows messages](https://docs.microsoft.com/windows/win32/winmsg/about-messages-and-message-queues). A series of overridable methods process these messages at the application, form, and control level. When these methods receive keyboard messages, they raise events that can be handled to get information about the keyboard input. In many cases, Windows Forms applications will be able to process all user input simply by handling these events. In other cases, an application may need to override one of the methods that process messages in order to intercept a particular message before it is received by the application, form, or control. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Keyboard events + +All Windows Forms controls inherit a set of events related to mouse and keyboard input. For example, a control can handle the event to determine the character code of a key that was pressed. For more information, see [Using keyboard events](events.md). + +## Methods that process user input messages + +Forms and controls have access to the interface and a set of overridable methods that process Windows messages at different points in the message queue. These methods all have a parameter, which encapsulates the low-level details of Windows messages. You can implement or override these methods to examine the message and then either consume the message or pass it on to the next consumer in the message queue. The following table presents the methods that process all Windows messages in Windows Forms. + +| Method | Notes | +|------------|-----------| +| | This method intercepts queued (also known as posted) Windows messages at the application level.| +| | This method intercepts Windows messages at the form and control level before they have been processed.| +| | This method processes Windows messages at the form and control level.| +| | This method performs the default processing of Windows messages at the form and control level. This provides the minimal functionality of a window.| +| | This method intercepts messages at the form and control level, after they have been processed. The style bit must be set for this method to be called.| + +Keyboard and mouse messages are also processed by an additional set of overridable methods that are specific to those types of messages. For more information, see the [Preprocessing keys](#preprocessing-keys) section. . + +## Types of keys + +Windows Forms identifies keyboard input as virtual-key codes that are represented by the bitwise enumeration. With the enumeration, you can combine a series of pressed keys to result in a single value. These values correspond to the values that accompany the **WM_KEYDOWN** and **WM_SYSKEYDOWN** Windows messages. You can detect most physical key presses by handling the or events. Character keys are a subset of the enumeration and correspond to the values that accompany the **WM_CHAR** and **WM_SYSCHAR** Windows messages. If the combination of pressed keys results in a character, you can detect the character by handling the event. + +## Order of keyboard events + +As listed previously, there are 3 keyboard related events that can occur on a control. The following sequence shows the general order of the events: + +01. The user pushes the "a" key, the key is preprocessed, dispatched, and a event occurs. +01. The user holds the "a" key, the key is preprocessed, dispatched, and a event occurs. + This event occurs multiple times as the user holds a key. +01. The user releases the "a" key, the key is preprocessed, dispatched and a event occurs. + +## Preprocessing keys + +Like other messages, keyboard messages are processed in the method of a form or control. However, before keyboard messages are processed, the method calls one or more methods that can be overridden to handle special character keys and physical keys. You can override these methods to detect and filter certain keys before the messages are processed by the control. The following table shows the action that is being performed and the related method that occurs, in the order that the method occurs. + +### Preprocessing for a KeyDown event + +|Action|Related method|Notes| +|------------|--------------------|-----------| +|Check for a command key such as an accelerator or menu shortcut.||This method processes a command key, which takes precedence over regular keys. If this method returns `true`, the key message is not dispatched and a key event does not occur. If it returns `false`, is called`.`| +|Check for a special key that requires preprocessing or a normal character key that should raise a event and be dispatched to a control.||If the method returns `true`, it means the control is a regular character and a event is raised. If `false`, is called. **Note:** To ensure a control gets a key or combination of keys, you can handle the event and set of the to `true` for the key or keys you want.| +|Check for a navigation key (ESC, TAB, Return, or arrow keys).||This method processes a physical key that employs special functionality within the control, such as switching focus between the control and its parent. If the immediate control does not handle the key, the is called on the parent control and so on to the topmost control in the hierarchy. If this method returns `true`, preprocessing is complete and a key event is not generated. If it returns `false`, a event occurs.| + +### Preprocessing for a KeyPress event + +|Action|Related method|Notes| +|------------|--------------------|-----------| +|Check to see the key is a normal character that should be processed by the control||If the character is a normal character, this method returns `true`, the event is raised and no further preprocessing occurs. Otherwise will be called.| +|Check to see if the character is a mnemonic (such as &OK on a button)||This method, similar to , will be called up the control hierarchy. If the control is a container control, it checks for mnemonics by calling on itself and its child controls. If returns `true`, a event does not occur.| + +## Processing keyboard messages + +After keyboard messages reach the method of a form or control, they are processed by a set of methods that can be overridden. Each of these methods returns a value specifying whether the keyboard message has been processed and consumed by the control. If one of the methods returns `true`, then the message is considered handled, and it is not passed to the control's base or parent for further processing. Otherwise, the message stays in the message queue and may be processed in another method in the control's base or parent. The following table presents the methods that process keyboard messages. + +|Method|Notes| +|------------|-----------| +||This method processes all keyboard messages that are received by the method of the control.| +||This method sends the keyboard message to the control's parent. If returns `true`, no key event is generated, otherwise is called.| +||This method raises the , , and events, as appropriate.| + +## Overriding keyboard methods + +There are many methods available for overriding when a keyboard message is preprocessed and processed; however, some methods are much better choices than others. Following table shows tasks you might want to accomplish and the best way to override the keyboard methods. For more information on overriding methods, see [Inheritance (C# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/inheritance.md#abstract-and-virtual-methods) or [Inheritance (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/inheritance-basics.md#overriding-properties-and-methods-in-derived-classes) + +|Task|Method| +|----------|------------| +|Intercept a navigation key and raise a event. For example you want TAB and Return to be handled in a text box.|Override . **Note:** Alternatively, you can handle the event and set of the to `true` for the key or keys you want.| +|Perform special input or navigation handling on a control. For example, you want the use of arrow keys in your list control to change the selected item.|Override | +|Intercept a navigation key and raise a event. For example in a spin-box control you want multiple arrow key presses to accelerate progression through the items.|Override .| +|Perform special input or navigation handling during a event. For example, in a list control holding down the "r" key skips between items that begin with the letter r.|Override | +|Perform custom mnemonic handling; for example, you want to handle mnemonics on owner-drawn buttons contained in a toolbar.|Override .| + +## See also + +- +- +- +- [Using keyboard events (Windows Forms .NET)](events.md) +- [How to modify keyboard key events (Windows Forms .NET)](how-to-change-key-press.md) +- [How to Check for modifier key presses (Windows Forms .NET)](how-to-check-modifier-key.md) +- [How to simulate keyboard events (Windows Forms .NET)](how-to-simulate-events.md) +- [How to handle keyboard input messages in the form (Windows Forms .NET)](how-to-handle-forms.md) +- [Add a control (Windows Forms .NET)](../controls/how-to-add-to-a-form.md) diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..a2cca52a8c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.Designer.cs @@ -0,0 +1,112 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.newTextBox1 = new project.NewTextBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // comboBox1 + // + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "item 1", + "item 2", + "item 3", + "item 4"}); + this.comboBox1.Location = new System.Drawing.Point(93, 13); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(121, 23); + this.comboBox1.TabIndex = 1; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(12, 41); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(100, 23); + this.textBox1.TabIndex = 2; + this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress); + // + // textBox2 + // + this.textBox2.Location = new System.Drawing.Point(12, 70); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(100, 23); + this.textBox2.TabIndex = 3; + this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress); + // + // newTextBox1 + // + this.newTextBox1.Location = new System.Drawing.Point(275, 41); + this.newTextBox1.Name = "newTextBox1"; + this.newTextBox1.Size = new System.Drawing.Size(100, 23); + this.newTextBox1.TabIndex = 4; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.newTextBox1); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.ComboBox comboBox1; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.TextBox textBox2; + private NewTextBox newTextBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.cs new file mode 100644 index 0000000000..55b1d694f9 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + comboBox1.Focus(); + SendKeys.Send("%+{DOWN}"); + } + + private void Form1_Load(object sender, EventArgs e) + { + + } + + private void Form1_KeyPress(object sender, KeyPressEventArgs e) + { + + } + + // + private void textBox1_KeyPress(object sender, KeyPressEventArgs e) + { + if (e.KeyChar == 'a' || e.KeyChar == 'A') + e.Handled = true; + } + // + + // + private void textBox2_KeyPress(object sender, KeyPressEventArgs e) + { + if (e.KeyChar == 'a' || e.KeyChar == 'A') + { + e.KeyChar = '!'; + e.Handled = false; + } + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.Designer.cs new file mode 100644 index 0000000000..e114143214 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.Designer.cs @@ -0,0 +1,78 @@ +namespace project +{ + partial class Form2 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // comboBox1 + // + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "item 1", + "item 2", + "item 3", + "item 4"}); + this.comboBox1.Location = new System.Drawing.Point(93, 13); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(121, 23); + this.comboBox1.TabIndex = 1; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.ComboBox comboBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.cs new file mode 100644 index 0000000000..45eb07103c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form2 : Form + { + public Form2() + { + InitializeComponent(); + } + + // + [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("USER32.DLL")] + public static extern bool SetForegroundWindow(IntPtr hWnd); + + private void button1_Click(object sender, EventArgs e) + { + IntPtr calcWindow = FindWindow(null, "Calculator"); + + if (SetForegroundWindow(calcWindow)) + SendKeys.Send("10{+}10="); + } + // + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/NewTextBox.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/NewTextBox.cs new file mode 100644 index 0000000000..1e942a61f1 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/NewTextBox.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + class NewTextBox : TextBox + { + // + public override bool PreProcessMessage(ref Message m) + { + const int WM_KEYDOWN = 0x100; + + if (m.Msg == WM_KEYDOWN) + { + Keys keyCode = (Keys)m.WParam & Keys.KeyCode; + + // Detect F1 through F9. + m.WParam = keyCode switch + { + Keys.F1 => (IntPtr)Keys.D1, + Keys.F2 => (IntPtr)Keys.D2, + Keys.F3 => (IntPtr)Keys.D3, + Keys.F4 => (IntPtr)Keys.D4, + Keys.F5 => (IntPtr)Keys.D5, + Keys.F6 => (IntPtr)Keys.D6, + Keys.F7 => (IntPtr)Keys.D7, + Keys.F8 => (IntPtr)Keys.D8, + Keys.F9 => (IntPtr)Keys.D9, + Keys.F10 => (IntPtr)Keys.D0, + _ => m.WParam + }; + } + + // Send all other messages to the base method. + return base.PreProcessMessage(ref m); + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Program.cs new file mode 100644 index 0000000000..8468dcc8a3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/project.csproj new file mode 100644 index 0000000000..83927472a6 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/csharp/project.csproj @@ -0,0 +1,18 @@ + + + + WinExe + net5.0-windows + true + + + + + Form + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.Designer.vb new file mode 100644 index 0000000000..28ea2bff1e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.Designer.vb @@ -0,0 +1,93 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.ComboBox1 = New System.Windows.Forms.ComboBox() + Me.TextBox1 = New System.Windows.Forms.TextBox() + Me.TextBox2 = New System.Windows.Forms.TextBox() + Me.NewTextBox1 = New projectvb.NewTextBox() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'ComboBox1 + ' + Me.ComboBox1.FormattingEnabled = True + Me.ComboBox1.Items.AddRange(New Object() {"item 1", "item 2", "item 3", "item 4"}) + Me.ComboBox1.Location = New System.Drawing.Point(93, 12) + Me.ComboBox1.Name = "ComboBox1" + Me.ComboBox1.Size = New System.Drawing.Size(121, 23) + Me.ComboBox1.TabIndex = 1 + ' + 'TextBox1 + ' + Me.TextBox1.Location = New System.Drawing.Point(12, 41) + Me.TextBox1.Name = "TextBox1" + Me.TextBox1.Size = New System.Drawing.Size(100, 23) + Me.TextBox1.TabIndex = 2 + ' + 'TextBox2 + ' + Me.TextBox2.Location = New System.Drawing.Point(12, 70) + Me.TextBox2.Name = "TextBox2" + Me.TextBox2.Size = New System.Drawing.Size(100, 23) + Me.TextBox2.TabIndex = 3 + ' + 'NewTextBox1 + ' + Me.NewTextBox1.Location = New System.Drawing.Point(208, 138) + Me.NewTextBox1.Name = "NewTextBox1" + Me.NewTextBox1.Size = New System.Drawing.Size(100, 23) + Me.NewTextBox1.TabIndex = 4 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.NewTextBox1) + Me.Controls.Add(Me.TextBox2) + Me.Controls.Add(Me.TextBox1) + Me.Controls.Add(Me.ComboBox1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend Button1 As Windows.Forms.Button + Friend ComboBox1 As Windows.Forms.ComboBox + Friend TextBox1 As Windows.Forms.TextBox + Friend TextBox2 As Windows.Forms.TextBox + Friend NewTextBox1 As NewTextBox +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.vb new file mode 100644 index 0000000000..006d0665e6 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form1.vb @@ -0,0 +1,35 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + + AddHandler Button1.Click, AddressOf Button1_Click + AddHandler TextBox1.KeyPress, AddressOf TextBox1_KeyPress + AddHandler TextBox2.KeyPress, AddressOf TextBox2_KeyPress + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + ComboBox1.Focus() + SendKeys.Send("%+{DOWN}") + End Sub + + ' + Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) + If e.KeyChar = "a"c Or e.KeyChar = "A"c Then + e.Handled = True + End If + End Sub + ' + + ' + Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) + If e.KeyChar = "a"c Or e.KeyChar = "A"c Then + e.KeyChar = "!"c + e.Handled = False + End If + End Sub + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.Designer.vb new file mode 100644 index 0000000000..0971197fd2 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.Designer.vb @@ -0,0 +1,50 @@ + +Partial Class Form2 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Form2 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Button1) + Me.Name = "Form2" + Me.Text = "Form1 vb" + Me.ResumeLayout(False) + + End Sub + + Friend Button1 As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.vb new file mode 100644 index 0000000000..f3898476bb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Form2.vb @@ -0,0 +1,28 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form2 + + Public Sub New() + InitializeComponent() + + AddHandler Button1.Click, AddressOf Button1_Click + + End Sub + + ' + + Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr : End Function + + + Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean : End Function + + Private Sub Button1_Click(sender As Object, e As EventArgs) + Dim hCalcWindow As IntPtr = FindWindow(Nothing, "Calculator") + + If SetForegroundWindow(hCalcWindow) Then + SendKeys.Send("10{+}10=") + End If + End Sub + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/My Project/app.manifest b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/My Project/app.manifest new file mode 100644 index 0000000000..0da1f6d0ba --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/My Project/app.manifest @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/NewTextBox.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/NewTextBox.vb new file mode 100644 index 0000000000..377292d061 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/NewTextBox.vb @@ -0,0 +1,32 @@ +Imports System.Windows.Forms + +Public Class NewTextBox + Inherits TextBox + + ' + Public Overrides Function PreProcessMessage(ByRef m As Message) As Boolean + + Const WM_KEYDOWN = &H100 + + If m.Msg = WM_KEYDOWN Then + Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode + + Select Case keyCode + Case Keys.F1 : m.WParam = CType(Keys.D1, IntPtr) + Case Keys.F2 : m.WParam = CType(Keys.D2, IntPtr) + Case Keys.F3 : m.WParam = CType(Keys.D3, IntPtr) + Case Keys.F4 : m.WParam = CType(Keys.D4, IntPtr) + Case Keys.F5 : m.WParam = CType(Keys.D5, IntPtr) + Case Keys.F6 : m.WParam = CType(Keys.D6, IntPtr) + Case Keys.F7 : m.WParam = CType(Keys.D7, IntPtr) + Case Keys.F8 : m.WParam = CType(Keys.D8, IntPtr) + Case Keys.F9 : m.WParam = CType(Keys.D9, IntPtr) + Case Keys.F10 : m.WParam = CType(Keys.D0, IntPtr) + End Select + End If + + Return MyBase.PreProcessMessage(m) + End Function + ' + +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Program.vb new file mode 100644 index 0000000000..eeafc35385 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/projectvb.vbproj new file mode 100644 index 0000000000..d476bc115d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-change-key-press/vb/projectvb.vbproj @@ -0,0 +1,19 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + Form + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..4758737948 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.Designer.cs @@ -0,0 +1,74 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(12, 41); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(100, 23); + this.textBox1.TabIndex = 2; + this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown); + this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox textBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.cs new file mode 100644 index 0000000000..23c55d117e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + } + + // + // Event only raised when non-modifier key is pressed + private void textBox1_KeyPress(object sender, KeyPressEventArgs e) + { + if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) + MessageBox.Show("KeyPress " + Keys.Shift); + } + + // Event raised as soon as shift is pressed + private void textBox1_KeyDown(object sender, KeyEventArgs e) + { + if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) + MessageBox.Show("KeyDown " + Keys.Shift); + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Program.cs new file mode 100644 index 0000000000..8468dcc8a3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/project.csproj new file mode 100644 index 0000000000..9a8f0f1a64 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/csharp/project.csproj @@ -0,0 +1,15 @@ + + + + WinExe + net5.0-windows + true + + + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.Designer.vb new file mode 100644 index 0000000000..e496d23b81 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.Designer.vb @@ -0,0 +1,61 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.TextBox1 = New System.Windows.Forms.TextBox() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'TextBox1 + ' + Me.TextBox1.Location = New System.Drawing.Point(12, 40) + Me.TextBox1.Name = "TextBox1" + Me.TextBox1.Size = New System.Drawing.Size(100, 23) + Me.TextBox1.TabIndex = 1 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.TextBox1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend Button1 As Windows.Forms.Button + Friend TextBox1 As Windows.Forms.TextBox +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.vb new file mode 100644 index 0000000000..0b0be3d75d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Form1.vb @@ -0,0 +1,33 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + + AddHandler Button1.Click, AddressOf Button1_Click + AddHandler TextBox1.KeyPress, AddressOf TextBox1_KeyPress + AddHandler TextBox1.KeyDown, AddressOf TextBox1_KeyDown + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + End Sub + + ' + ' Event only raised when non-modifier key is pressed + Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) + If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then + MessageBox.Show("KeyPress " & [Enum].GetName(GetType(Keys), Keys.Shift)) + End If + End Sub + + ' Event raised as soon as shift is pressed + Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) + If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then + MessageBox.Show("KeyPress " & [Enum].GetName(GetType(Keys), Keys.Shift)) + End If + End Sub + ' + +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/My Project/app.manifest b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/My Project/app.manifest new file mode 100644 index 0000000000..0da1f6d0ba --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/My Project/app.manifest @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Program.vb new file mode 100644 index 0000000000..eeafc35385 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/projectvb.vbproj new file mode 100644 index 0000000000..6c27ad4296 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-check-modifier-key/vb/projectvb.vbproj @@ -0,0 +1,21 @@ + + + + WinExe + net5.0-windows + true + Sub Main + My Project\app.manifest + + + + + Form + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..57ded173f6 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.Designer.cs @@ -0,0 +1,73 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(12, 41); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(100, 23); + this.textBox1.TabIndex = 2; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.button1); + this.KeyPreview = true; + this.Name = "Form1"; + this.Text = "Form1"; + this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox textBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.cs new file mode 100644 index 0000000000..7081ec4908 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // Event only raised when non-modifier key is pressed + private void textBox1_KeyPress(object sender, KeyPressEventArgs e) + { + + } + + // Event raised as soon as shift is pressed + private void textBox1_KeyDown(object sender, KeyEventArgs e) + { + + } + + // + // Detect all numeric characters at the form level and consume 1,4, and 7. + // Form.KeyPreview must be set to true for this event handler to be called. + void Form1_KeyPress(object sender, KeyPressEventArgs e) + { + if (e.KeyChar >= 48 && e.KeyChar <= 57) + { + MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed."); + + switch (e.KeyChar) + { + case (char)49: + case (char)52: + case (char)55: + MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed."); + e.Handled = true; + break; + } + } + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Program.cs new file mode 100644 index 0000000000..8468dcc8a3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/project.csproj new file mode 100644 index 0000000000..9a8f0f1a64 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/csharp/project.csproj @@ -0,0 +1,15 @@ + + + + WinExe + net5.0-windows + true + + + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.Designer.vb new file mode 100644 index 0000000000..17fccdc49d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.Designer.vb @@ -0,0 +1,62 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.TextBox1 = New System.Windows.Forms.TextBox() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'TextBox1 + ' + Me.TextBox1.Location = New System.Drawing.Point(12, 40) + Me.TextBox1.Name = "TextBox1" + Me.TextBox1.Size = New System.Drawing.Size(100, 23) + Me.TextBox1.TabIndex = 1 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.TextBox1) + Me.Controls.Add(Me.Button1) + Me.KeyPreview = True + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend Button1 As Windows.Forms.Button + Friend TextBox1 As Windows.Forms.TextBox +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.vb new file mode 100644 index 0000000000..9e7bfa64f3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Form1.vb @@ -0,0 +1,31 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + AddHandler Me.KeyPress, AddressOf Form1_KeyPress + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + End Sub + + ' + ' Detect all numeric characters at the form level and consume 1,4, and 7. + ' Form.KeyPreview must be set to true for this event handler to be called. + Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) + If e.KeyChar >= Chr(48) And e.KeyChar <= Chr(57) Then + MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.") + + Select Case e.KeyChar + Case Chr(49), Chr(52), Chr(55) + MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.") + e.Handled = True + End Select + End If + + End Sub + ' + +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/My Project/app.manifest b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/My Project/app.manifest new file mode 100644 index 0000000000..0da1f6d0ba --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/My Project/app.manifest @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Program.vb new file mode 100644 index 0000000000..eeafc35385 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/projectvb.vbproj new file mode 100644 index 0000000000..6c27ad4296 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-handle-forms/vb/projectvb.vbproj @@ -0,0 +1,21 @@ + + + + WinExe + net5.0-windows + true + Sub Main + My Project\app.manifest + + + + + Form + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..b48911f91c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.Designer.cs @@ -0,0 +1,78 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // comboBox1 + // + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "item 1", + "item 2", + "item 3", + "item 4"}); + this.comboBox1.Location = new System.Drawing.Point(93, 13); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(121, 23); + this.comboBox1.TabIndex = 1; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.ComboBox comboBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.cs new file mode 100644 index 0000000000..ad6de45e8d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // + private void button1_Click(object sender, EventArgs e) + { + comboBox1.Focus(); + SendKeys.Send("%+{DOWN}"); + } + // + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.Designer.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.Designer.cs new file mode 100644 index 0000000000..e114143214 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.Designer.cs @@ -0,0 +1,78 @@ +namespace project +{ + partial class Form2 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // comboBox1 + // + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "item 1", + "item 2", + "item 3", + "item 4"}); + this.comboBox1.Location = new System.Drawing.Point(93, 13); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(121, 23); + this.comboBox1.TabIndex = 1; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.ComboBox comboBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.cs new file mode 100644 index 0000000000..45eb07103c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form2 : Form + { + public Form2() + { + InitializeComponent(); + } + + // + [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("USER32.DLL")] + public static extern bool SetForegroundWindow(IntPtr hWnd); + + private void button1_Click(object sender, EventArgs e) + { + IntPtr calcWindow = FindWindow(null, "Calculator"); + + if (SetForegroundWindow(calcWindow)) + SendKeys.Send("10{+}10="); + } + // + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Program.cs new file mode 100644 index 0000000000..074cd3e93e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form2()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/project.csproj new file mode 100644 index 0000000000..83927472a6 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/csharp/project.csproj @@ -0,0 +1,18 @@ + + + + WinExe + net5.0-windows + true + + + + + Form + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.Designer.vb new file mode 100644 index 0000000000..e4e8b847b4 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.Designer.vb @@ -0,0 +1,62 @@ + _ +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.ComboBox1 = New System.Windows.Forms.ComboBox() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'ComboBox1 + ' + Me.ComboBox1.FormattingEnabled = True + Me.ComboBox1.Items.AddRange(New Object() {"item 1", "item 2", "item 3", "item 4"}) + Me.ComboBox1.Location = New System.Drawing.Point(93, 12) + Me.ComboBox1.Name = "ComboBox1" + Me.ComboBox1.Size = New System.Drawing.Size(121, 23) + Me.ComboBox1.TabIndex = 1 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.ComboBox1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + + End Sub + + Friend Button1 As Windows.Forms.Button + Friend ComboBox1 As Windows.Forms.ComboBox +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.vb new file mode 100644 index 0000000000..d13c81b62f --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form1.vb @@ -0,0 +1,19 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + + AddHandler Button1.Click, AddressOf Button1_Click + + End Sub + + ' + Private Sub Button1_Click(sender As Object, e As EventArgs) + ComboBox1.Focus() + SendKeys.Send("%+{DOWN}") + End Sub + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.Designer.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.Designer.vb new file mode 100644 index 0000000000..0971197fd2 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.Designer.vb @@ -0,0 +1,50 @@ + +Partial Class Form2 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Form2 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Button1) + Me.Name = "Form2" + Me.Text = "Form1 vb" + Me.ResumeLayout(False) + + End Sub + + Friend Button1 As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.resx b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.vb new file mode 100644 index 0000000000..f3898476bb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Form2.vb @@ -0,0 +1,28 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form2 + + Public Sub New() + InitializeComponent() + + AddHandler Button1.Click, AddressOf Button1_Click + + End Sub + + ' + + Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr : End Function + + + Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean : End Function + + Private Sub Button1_Click(sender As Object, e As EventArgs) + Dim hCalcWindow As IntPtr = FindWindow(Nothing, "Calculator") + + If SetForegroundWindow(hCalcWindow) Then + SendKeys.Send("10{+}10=") + End If + End Sub + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Program.vb new file mode 100644 index 0000000000..905ccb3e72 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form2()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/projectvb.vbproj new file mode 100644 index 0000000000..d476bc115d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/snippets/how-to-simulate-events/vb/projectvb.vbproj @@ -0,0 +1,19 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + Form + + + Form + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-keyboard/validation.md b/dotnet-desktop-guide/net/winforms/input-keyboard/validation.md new file mode 100644 index 0000000000..c4bbc68159 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-keyboard/validation.md @@ -0,0 +1,101 @@ +--- +title: "User input validation" +description: Learn about several ways that you can use Windows Forms to validate user input in your applications. +ms.date: 10/26/2020 +ms.topic: overview +helpviewer_keywords: + - "Windows Forms, validating user input" + - "validation [Windows Forms], Windows Forms user input" + - "user input [Windows Forms], validating in Windows Forms" + - "validating user input [Windows Forms], Windows Forms" +--- +# Overview of how to validate user input (Windows Forms .NET) + +When users enter data into your application, you may want to verify that the data is valid before your application uses it. You may require that certain text fields not be zero-length, that a field formatted as a telephone number, or that a string doesn't contain invalid characters. Windows Forms provides several ways for you to validate input in your application. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## MaskedTextBox Control + +If you need to require users to enter data in a well-defined format, such as a telephone number or a part number, you can accomplish this quickly and with minimal code by using the control. A *mask* is a string made up of characters from a masking language that specifies which characters can be entered at any given position in the text box. The control displays a set of prompts to the user. If the user types an incorrect entry, for example, the user types a letter when a digit is required, the control will automatically reject the input. + +The masking language that is used by is flexible. It allows you to specify required characters, optional characters, literal characters, such as hyphens and parentheses, currency characters, and date separators. The control also works well when bound to a data source. The event on a data binding can be used to reformat incoming data to comply with the mask, and the event can be used to reformat outgoing data to comply with the specifications of the data field. + + + +## Event-driven validation + +If you want full programmatic control over validation, or need complex validation checks, you should use the validation events that are built into most Windows Forms controls. Each control that accepts free-form user input has a event that will occur whenever the control requires data validation. In the event-handling method, you can validate user input in several ways. For example, if you have a text box that must contain a postal code, you can do the validation in the following ways: + +- If the postal code must belong to a specific group of zip codes, you can do a string comparison on the input to validate the data entered by the user. For example, if the postal code must be in the set `{10001, 10002, 10003}`, then you can use a string comparison to validate the data. + +- If the postal code must be in a specific form, you can use regular expressions to validate the data entered by the user. For example, to validate the form `#####` or `#####-####`, you can use the regular expression `^(\d{5})(-\d{4})?$`. To validate the form `A#A #A#`, you can use the regular expression `[A-Z]\d[A-Z] \d[A-Z]\d`. For more information about regular expressions, see [.NET Regular Expressions](/dotnet/standard/base-types/regular-expressions) and [Regular Expression Examples](/dotnet/standard/base-types/regular-expression-example-scanning-for-hrefs). + +- If the postal code must be a valid United States Zip code, you could call a Zip code Web service to validate the data entered by the user. + +The event is supplied an object of type . If you determine that the control's data isn't valid, cancel the event by setting this object's property to `true`. If you don't set the property, Windows Forms will assume that validation succeeded for that control and raise the event. + +For a code example that validates an email address in a , see the event reference. + +### Event-driven validation data-bound controls + +Validation is useful when you have bound your controls to a data source, such as a database table. By using validation, you can make sure that your control's data satisfies the format required by the data source, and that it doesn't contain any special characters such as quotation marks and back slashes that might be unsafe. + +When you use data binding, the data in your control is synchronized with the data source during execution of the event. If you cancel the event, the data won't be synchronized with the data source. + +> [!IMPORTANT] +> If you have custom validation that takes place after the event, it won't affect the data binding. For example, if you have code in a event that attempts to cancel the data binding, the data binding will still occur. In this case, to perform validation in the event, change the control's [`Binding.DataSourceUpdateMode`](xref:System.Windows.Forms.Binding.DataSourceUpdateMode) property from to , and add `your-control.DataBindings["field-name"].WriteValue()` to your validation code. + +## Implicit and explicit validation + +So when does a control's data get validated? This is up to you, the developer. You can use either implicit or explicit validation, depending on the needs of your application. + +### Implicit validation + +The implicit validation approach validates data as the user enters it. Validate the data by reading the keys as they're pressed, or more commonly whenever the user takes the input focus away from the control. This approach is useful when you want to give the user immediate feedback about the data as they're working. + +If you want to use implicit validation for a control, you must set that control's property to or . If you cancel the event, the behavior of the control will be determined by what value you assigned to . If you assigned , canceling the event will cause the event not to occur. Input focus will remain on the current control until the user changes the data to a valid format. If you assigned , the event won't occur when you cancel the event, but focus will still change to the next control. + +Assigning to the property prevents implicit validation altogether. To validate your controls, you'll have to use explicit validation. + +### Explicit validation + +The explicit validation approach validates data at one time. You can validate the data in response to a user action, such as clicking a **Save** button or a **Next** link. When the user action occurs, you can trigger explicit validation in one of the following ways: + +- Call to validate the last control to have lost focus. +- Call to validate all child controls in a form or container control. +- Call a custom method to validate the data in the controls manually. + +### Default implicit validation behavior for controls + +Different Windows Forms controls have different defaults for their property. The following table shows the most common controls and their defaults. + +| Control | Default Validation Behavior | +|------------------------------------------------|-----------------------------------------------------------------| +| | | +| | | +| | Property not exposed in Visual Studio | +| | Property not exposed in Visual Studio | +| | | +| | | + +## Closing the form and overriding Validation + +When a control maintains focus because the data it contains is invalid, it's impossible to close the parent form in one of the usual ways: + +- By clicking the **Close** button. +- By selecting the **System** > **Close** menu. +- By calling the method programmatically. + +However, in some cases, you might want to let the user close the form regardless of whether the values in the controls are valid. You can override validation and close a form that still contains invalid data by creating a handler for the form's event. In the event, set the property to `false`. This forces the form to close. For more information and an example, see . + +> [!NOTE] +> If you force the form to close in this manner, any data in the form's controls that has not already been saved is lost. In addition, modal forms don't validate the contents of controls when they're closed. You can still use control validation to lock focus to a control, but you don't have to be concerned about the behavior associated with closing the form. + +## See also + +- [Using keyboard events (Windows Forms .NET)](events.md) +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/drag-and-drop.md b/dotnet-desktop-guide/net/winforms/input-mouse/drag-and-drop.md new file mode 100644 index 0000000000..f7c538b671 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/drag-and-drop.md @@ -0,0 +1,95 @@ +--- +title: "Drag-and-drop mouse behaviors" +description: Learn about how drag-and-drop works on Windows Forms, including how to perform drag-and-drop with the mouse. +ms.date: 10/26/2020 +ms.topic: conceptual +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: +- "drag and drop [Windows Forms], Windows Forms" +- "Windows Forms, drag and drop" +--- + +# Drag-and-drop mouse behavior overview (Windows Forms .NET) + +Windows Forms includes a set of methods, events, and classes that implement drag-and-drop behavior. This topic provides an overview of the drag-and-drop support in Windows Forms. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Drag-and-drop events + +There are two categories of events in a drag and drop operation: events that occur on the current target of the drag-and-drop operation, and events that occur on the source of the drag and drop operation. To perform drag-and-drop operations, you must handle these events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations. + +## Events on the current drop target + +The following table shows the events that occur on the current target of a drag-and-drop operation. + +| Mouse Event | Description | +|-----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| | This event occurs when an object is dragged into the control's bounds. The handler for this event receives an argument of type . | +| | This event occurs when an object is dragged while the mouse pointer is within the control's bounds. The handler for this event receives an argument of type . | +| | This event occurs when a drag-and-drop operation is completed. The handler for this event receives an argument of type . | +| | This event occurs when an object is dragged out of the control's bounds. The handler for this event receives an argument of type . | + +The class provides the location of the mouse pointer, the current state of the mouse buttons and modifier keys of the keyboard, the data being dragged, and values that specify the operations allowed by the source of the drag event and the target drop effect for the operation. + +## Events on the drop source + +The following table shows the events that occur on the source of the drag-and-drop operation. + +|Mouse Event|Description| +|-----------------|-----------------| +||This event occurs during a drag operation. It provides an opportunity to give a visual cue to the user that the drag-and-drop operation is occurring, such as changing the mouse pointer. The handler for this event receives an argument of type .| +||This event is raised during a drag-and-drop operation and enables the drag source to determine whether the drag-and-drop operation should be canceled. The handler for this event receives an argument of type .| + +The class provides the current state of the mouse buttons and modifier keys of the keyboard, a value specifying whether the ESC key was pressed, and a value that can be set to specify whether the drag-and-drop operation should continue. + +## Performing drag-and-drop + +Drag-and-drop operations always involve two components, the **drag source** and the **drop target**. To start a drag-and-drop operation, designate a control as the source and handle the event. In the event handler, call the method providing the data associated with the drop and the a value. + +Set the target control's property set to `true` to allow that control to accept a drag-and-drop operation. The target handles two events, first an event in response to the drag being over the control, such as . And a second event which is the drop action itself, . + +The following example demonstrates a drag from a control to a . When the drag is completed, the `TextBox` responds by assigning the label's text to itself. + +```csharp +// Initiate the drag +private void label1_MouseDown(object sender, MouseEventArgs e) => + DoDragDrop(((Label)sender).Text, DragDropEffects.All); + +// Set the effect filter and allow the drop on this control +private void textBox1_DragOver(object sender, DragEventArgs e) => + e.Effect = DragDropEffects.All; + +// React to the drop on this control +private void textBox1_DragDrop(object sender, DragEventArgs e) => + textBox1.Text = (string)e.Data.GetData(typeof(string)); +``` + +```vb +' Initiate the drag +Private Sub Label1_MouseDown(sender As Object, e As MouseEventArgs) + DoDragDrop(DirectCast(sender, Label).Text, DragDropEffects.All) +End Sub + +' Set the effect filter and allow the drop on this control +Private Sub TextBox1_DragOver(sender As Object, e As DragEventArgs) + e.Effect = DragDropEffects.All +End Sub + +' React to the drop on this control +Private Sub TextBox1_DragDrop(sender As Object, e As DragEventArgs) + TextBox1.Text = e.Data.GetData(GetType(String)) +End Sub +``` + +For more information about the drag effects, see and . + +## See also + +- [Overview of using the mouse (Windows Forms .NET)](overview.md) +- +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/events.md b/dotnet-desktop-guide/net/winforms/input-mouse/events.md new file mode 100644 index 0000000000..89b9c308fc --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/events.md @@ -0,0 +1,151 @@ +--- +title: "Using mouse events" +description: Overview of using mouse events to handle mouse input. Each event may provide associated data. This article provides a list of mouse-related events. +ms.date: 10/26/2020 +ms.topic: conceptual +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Click event [Windows Forms]" + - "mouse [Windows Forms], mouse events" + - "Click event" + - "MouseClick event" + - "DoubleClick event" + - "MouseDown event" + - "MouseEnter event" + - "MouseHover event" + - "MouseLeave event" + - "MouseMove event" + - "MouseUp event" + - "MouseWheel event" + - "mouse events" + - "events [Windows Forms], mouse" +--- + +# Using mouse events (Windows Forms .NET) + +Most Windows Forms programs process mouse input by handling the mouse events. This article provides an overview of the mouse events, including details on when to use each event and the data that is supplied for each event. For more information about events in general, see [Events overview (Windows Forms .NET)](../forms/events.md). + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Mouse events + +The primary way to respond to mouse input is to handle mouse events. The following table shows the mouse events and describes when they're raised. + +| Mouse Event | Description | +|------------------------------------------------------|---------------------------------------------------------| +| | This event occurs when the mouse button is released, typically before the event. The handler for this event receives an argument of type . Handle this event when you only need to determine when a click occurs. | +| | This event occurs when the user clicks the control with the mouse. The handler for this event receives an argument of type . Handle this event when you need to get information about the mouse when a click occurs. | +| | This event occurs when the control is double-clicked. The handler for this event receives an argument of type . Handle this event when you only need to determine when a double-click occurs. | +| | This event occurs when the user double-clicks the control with the mouse. The handler for this event receives an argument of type . Handle this event when you need to get information about the mouse when a double-click occurs. | +| | This event occurs when the mouse pointer is over the control and the user presses a mouse button. The handler for this event receives an argument of type . | +| | This event occurs when the mouse pointer enters the border or client area of the control, depending on the type of control. The handler for this event receives an argument of type . | +| | This event occurs when the mouse pointer stops and rests over the control. The handler for this event receives an argument of type . | +| | This event occurs when the mouse pointer leaves the border or client area of the control, depending on the type of the control. The handler for this event receives an argument of type . | +| | This event occurs when the mouse pointer moves while it is over a control. The handler for this event receives an argument of type . | +| | This event occurs when the mouse pointer is over the control and the user releases a mouse button. The handler for this event receives an argument of type . | +| | This event occurs when the user rotates the mouse wheel while the control has focus. The handler for this event receives an argument of type . You can use the property of to determine how far the mouse has scrolled. | + +## Mouse information + +A is sent to the handlers of mouse events related to clicking a mouse button and tracking mouse movements. provides information about the current state of the mouse, including the location of the mouse pointer in client coordinates, which mouse buttons are pressed, and whether the mouse wheel has scrolled. Several mouse events, such as those that are raised when the mouse pointer has entered or left the bounds of a control, send an to the event handler with no further information. + +If you want to know the current state of the mouse buttons or the location of the mouse pointer, and you want to avoid handling a mouse event, you can also use the and properties of the class. returns information about which mouse buttons are currently pressed. The returns the screen coordinates of the mouse pointer and is equivalent to the value returned by . + +## Converting Between Screen and Client Coordinates + +Because some mouse location information is in client coordinates and some is in screen coordinates, you may need to convert a point from one coordinate system to the other. You can do this easily by using the and methods available on the class. + +## Standard Click event behavior + +If you want to handle mouse click events in the proper order, you need to know the order in which click events are raised in Windows Forms controls. All Windows Forms controls raise click events in the same order when any supported mouse button is pressed and released, except where noted in the following list for individual controls. The following list shows the order of events raised for a single mouse-button click: + +01. event. +01. event. +01. event. +01. event. + +The following is the order of events raised for a double mouse-button click: + +01. event. +01. event. +01. event. +01. event. +01. event. +01. event. + + This can vary, depending on whether the control in question has the style bit set to `true`. For more information about how to set a bit, see the method. + +01. event. +01. event. + +### Individual controls + +The following controls don't conform to the standard mouse click event behavior: + +- +- +- +- + + > [!NOTE] + > For the control, the event behavior detailed later occurs if the user clicks on the edit field, the button, or on an item within the list. + + - **Left click**: , + - **Right click**: No click events raised + - **Left double-click**: , ; , + - **Right double-click**: No click events raised + +- , , , , and controls + + > [!NOTE] + > The event behavior detailed later occurs when the user clicks anywhere within these controls. + + - **Left click**: , + - **Right click**: No click events raised + - **Left double-click**: , , , + - **Right double-click**: No click events raised + +- control + + > [!NOTE] + > The event behavior detailed later occurs only when the user clicks on the items in the control. No events are raised for clicks anywhere else on the control. In addition to the events described later, there are the and events, which may be of interest to you if you want to use validation with the control. + + - **Left click**: , + - **Right click**: , + - **Left double-click**: , ; , + - **Right double-click**: , ; , + +- control + + > [!NOTE] + > The event behavior detailed later occurs only when the user clicks on the items themselves or to the right of the items in the control. No events are raised for clicks anywhere else on the control. In addition to those described later, there are the , , , , , and events, which may be of interest to you if you want to use validation with the control. + + - **Left click**: , + - **Right click**: , + - **Left double-click**: , ; , + - **Right double-click**: , ; , + +## Painting behavior of toggle controls + +Toggle controls, such as the controls deriving from the class, have the following distinctive painting behavior in combination with mouse click events: + +01. The user presses the mouse button. +01. The control paints in the pressed state. +01. The event is raised. +01. The user releases the mouse button. +01. The control paints in the raised state. +01. The event is raised. +01. The event is raised. +01. The event is raised. + + > [!NOTE] + > If the user moves the pointer out of the toggle control while the mouse button is down (such as moving the mouse off the control while it is pressed), the toggle control will paint in the raised state and only the event occurs. The or events will not occur in this situation. + +## See also + +- [Overview of using the mouse (Windows Forms .NET)](overview.md) +- [Manage mouse pointers (Windows Forms .NET)](how-to-manage-cursor-pointer.md) +- [How to simulate mouse events (Windows Forms .NET)](how-to-simulate-events.md) +- diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/how-to-distinguish-between-clicks-and-double-clicks.md b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-distinguish-between-clicks-and-double-clicks.md new file mode 100644 index 0000000000..03acb942d4 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-distinguish-between-clicks-and-double-clicks.md @@ -0,0 +1,50 @@ +--- +title: "How to distinguish between single and double clicks" +description: Describes different ways to detect the difference between a single or double click with a control or form for Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "mouse [Windows Forms], click" + - "mouse [Windows Forms], double-click" + - "mouse clicks [Windows Forms], single versus double" +--- +# How to distinguish between clicks and double-clicks (Windows Forms .NET) + +Typically, a single *click* initiates a user interface action and a *double-click* extends the action. For example, one click usually selects an item, and a double-click edits the selected item. However, the Windows Forms click events do not easily accommodate a scenario where a click and a double-click perform incompatible actions, because an action tied to the or event is performed before the action tied to the or event. This topic demonstrates two solutions to this problem. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +One solution is to handle the double-click event and roll back the actions in the handling of the click event. In rare situations you may need to simulate click and double-click behavior by handling the event and by using the and properties of the class. You measure the time between clicks and if a second click occurs before the value of is reached and the click is within a rectangle defined by , perform the double-click action; otherwise, perform the click action. + +## To roll back a click action + +Ensure that the control you are working with has standard double-click behavior. If not, enable the control with the method. Handle the double-click event and roll back the click action as well as the double-click action. The following code example demonstrates a how to create a custom button with double-click enabled, as well as how to roll back the click action in the double-click event handling code. + +This code example uses a new button control that enables double-clicks: + +:::code language="csharp" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/DoubleClickButton.cs" id="DoubleClickButton"::: +:::code language="vb" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/DoubleClickButton.vb" id="DoubleClickButton"::: + +The following code demonstrates how a form changes the style of border based on a click or double-click of the new button control: + +:::code language="csharp" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.cs" id="RollbackForm"::: +:::code language="vb" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.vb" id="RollbackForm"::: + +## To distinguish between clicks + +Handle the event and determine the location and time span between clicks using the property and a component. Perform the appropriate action depending on whether a click or double-click takes place. The following code example demonstrates how this can be done. + +:::code language="csharp" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.cs"::: +:::code language="vb" source="snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.vb"::: + +## See also + +- [Overview of using the mouse (Windows Forms .NET)](overview.md) +- [Using mouse events (Windows Forms .NET)](events.md) +- [Manage mouse pointers (Windows Forms .NET)](how-to-manage-cursor-pointer.md) +- [How to simulate mouse events (Windows Forms .NET)](how-to-simulate-events.md) +- +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/how-to-manage-cursor-pointer.md b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-manage-cursor-pointer.md new file mode 100644 index 0000000000..1b32172a67 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-manage-cursor-pointer.md @@ -0,0 +1,60 @@ +--- +title: "How to manage mouse pointer" +description: Learn how to access, control, and change the mouse pointer in Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "pointers [Windows Forms], setting" + - "mouse pointers" + - "mouse cursors" + - "mouse pointers [Windows Forms], setting" + - "cursors [Windows Forms], setting" + - "mouse [Windows Forms], cursors" +--- +# Manage mouse pointers (Windows Forms .NET) + +The mouse *pointer*, which is sometimes referred to as the cursor, is a bitmap that specifies a focus point on the screen for user input with the mouse. This topic provides an overview of the mouse pointer in Windows Forms and describes some of the ways to modify and control the mouse pointer. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Accessing the mouse pointer + +The mouse pointer is represented by the class, and each has a property that specifies the pointer for that control. The class contains properties that describe the pointer, such as the and properties, and methods that can modify the appearance of the pointer, such as the , , and methods. + +The following example hides the cursor when the cursor is over a button: + +:::code language="csharp" source="snippets/how-to-manage-cursor-pointer/csharp/Form1.cs" id="ShowHideCursor"::: +:::code language="vb" source="snippets/how-to-manage-cursor-pointer/vb/Form1.vb" id="ShowHideCursor"::: + +## Controlling the mouse pointer + +Sometimes you may want to limit the area in which the mouse pointer can be used or change the position the mouse. You can get or set the current location of the mouse using the property of the . In addition, you can limit the area the mouse pointer can be used be setting the property. The clip area, by default, is the entire screen. + +The following example positions the mouse pointer between two buttons when they are clicked: + +:::code language="csharp" source="snippets/how-to-manage-cursor-pointer/csharp/Form1.cs" id="MoveCursor"::: +:::code language="vb" source="snippets/how-to-manage-cursor-pointer/vb/Form1.vb" id="MoveCursor"::: + +## Changing the mouse pointer + +Changing the mouse pointer is an important way of providing feedback to the user. For example, the mouse pointer can be modified in the handlers of the and events to tell the user that computations are occurring and to limit user interaction in the control. Sometimes, the mouse pointer will change because of system events, such as when your application is involved in a drag-and-drop operation. + +The primary way to change the mouse pointer is by setting the or property of a control to a new . For examples of changing the mouse pointer, see the code example in the class. In addition, the class exposes a set of objects for many different types of pointers, such as a pointer that resembles a hand. + +The following example changes the cursor of the mouse pointer for a button to a hand: + +:::code language="csharp" source="snippets/how-to-manage-cursor-pointer/csharp/Form1.cs" id="SetControlCursor"::: +:::code language="vb" source="snippets/how-to-manage-cursor-pointer/vb/Form1.vb" id="SetControlCursor"::: + +To display the wait pointer, which resembles an hourglass, whenever the mouse pointer is on the control, use the property of the class. + +## See also + +- [Overview of using the mouse (Windows Forms .NET)](overview.md) +- [Using mouse events (Windows Forms .NET)](events.md) +- [How to distinguish between clicks and double-clicks (Windows Forms .NET)](how-to-distinguish-between-clicks-and-double-clicks.md) +- [How to simulate mouse events (Windows Forms .NET)](how-to-simulate-events.md) +- +- diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/how-to-simulate-events.md b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-simulate-events.md new file mode 100644 index 0000000000..09612e9732 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/how-to-simulate-events.md @@ -0,0 +1,69 @@ +--- +title: "How to simulate mouse events" +description: Learn how to simulate mouse events in Windows Forms for .NET. +ms.date: 10/26/2020 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "mouse [Windows Forms], event simulation" + - "user input [Windows Forms], simulating" + - "SendKeys [Windows Forms], using" +--- +# How to simulate mouse events (Windows Forms .NET) + +Simulating mouse events in Windows Forms isn't as straight forward as simulating keyboard events. Windows Forms doesn't provide a helper class to move the mouse and invoke mouse-click actions. The only option for controlling the mouse is to use native Windows methods. If you're working with a custom control or a form, you can simulate a mouse event, but you can't directly control the mouse. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +## Events + +Most events have a corresponding method that invokes them, named in the pattern of `On` followed by `EventName`, such as `OnMouseMove`. This option is only possible within custom controls or forms, because these methods are protected and can't be accessed from outside the context of the control or form. The disadvantage to using a method such as `OnMouseMove` is that it doesn't actually control the mouse or interact with the control, it simply raises the associated event. For example, if you wanted to simulate hovering over an item in a , `OnMouseMove` and the `ListBox` doesn't visually react with a highlighted item under the cursor. + +These protected methods are available to simulate mouse events. + +- `OnMouseDown` +- `OnMouseEnter` +- `OnMouseHover` +- `OnMouseLeave` +- `OnMouseMove` +- `OnMouseUp` +- `OnMouseWheel` +- `OnMouseClick` +- `OnMouseDoubleClick` + +For more information about these events, see [Using mouse events (Windows Forms .NET)](events.md) + +## Invoke a click + +Considering most controls do something when clicked, like a button calling user code, or checkbox change its checked state, Windows Forms provides an easy way to trigger the click. Some controls, such as a combobox, don't do anything special when clicked and simulating a click has no effect on the control. + +### PerformClick + +The interface provides the method which simulates a click on the control. Both the and controls implement this interface. + +:::code language="csharp" source="snippets/how-to-simulate-events/csharp/Form1.cs" id="PerformClick"::: +:::code language="vb" source="snippets/how-to-simulate-events/vb/Form1.vb" id="PerformClick"::: + +### InvokeClick + +With a form a custom control, use the method to simulate a mouse click. This is a protected method that can only be called from within the form or a derived custom control. + +For example, the following code clicks a checkbox from `button1`. + +:::code language="csharp" source="snippets/how-to-simulate-events/csharp/Form1.cs" id="ClickCheckbox"::: +:::code language="vb" source="snippets/how-to-simulate-events/vb/Form1.vb" id="ClickCheckbox"::: + +## Use native Windows methods + +Windows provides methods you can call to simulate mouse movements and clicks such as [`User32.dll SendInput`](/windows/win32/api/winuser/nf-winuser-sendinput) and [`User32.dll SetCursorPos`](/windows/win32/api/winuser/nf-winuser-setcursorpos). The following example moves the mouse cursor to the center of a control: + +:::code language="csharp" source="snippets/how-to-simulate-events/csharp/Form2.cs" id="MoveCursor"::: +:::code language="vb" source="snippets/how-to-simulate-events/vb/Form2.vb" id="MoveCursor"::: + +## See also + +- [Overview of using the mouse (Windows Forms .NET)](overview.md) +- [Using mouse events (Windows Forms .NET)](events.md) +- [How to distinguish between clicks and double-clicks (Windows Forms .NET)](how-to-distinguish-between-clicks-and-double-clicks.md) +- [Manage mouse pointers (Windows Forms .NET)](how-to-manage-cursor-pointer.md) diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/overview.md b/dotnet-desktop-guide/net/winforms/input-mouse/overview.md new file mode 100644 index 0000000000..f47151edd4 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/overview.md @@ -0,0 +1,65 @@ +--- +title: "Overview of mouse input" +description: Learn about how mouse input works in Windows Forms for .NET. Mouse events are raised by forms and controls and represent the position and button state of the mouse. +ms.date: 10/26/2020 +ms.topic: overview +helpviewer_keywords: + - "Windows Forms, mouse input" + - "mouse [Windows Forms], input" +--- + +# Overview of using the mouse (Windows Forms .NET) + +Receiving and handling mouse input is an important part of every Windows application. You can handle mouse events to carry out an action in your application, or use mouse location information to perform hit testing or other actions. Also, you can change the way the controls in your application handle mouse input. This article describes these mouse events in detail, and how to obtain and change system settings for the mouse. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +In Windows Forms, user input is sent to applications in the form of [Windows messages](/windows/win32/winmsg/about-messages-and-message-queues). A series of overridable methods process these messages at the application, form, and control level. When these methods receive mouse messages, they raise events that can be handled to get information about the mouse input. In many cases, Windows Forms applications can process all user input simply by handling these events. In other cases, an application may override one of the methods that process messages to intercept a particular message before it's received by the application, form, or control. + +## Mouse Events + +All Windows Forms controls inherit a set of events related to mouse and keyboard input. For example, a control can handle the event to determine the location of a mouse click. For more information on the mouse events, see [Using mouse events](events.md). + +## Mouse location and hit-testing + +When the user moves the mouse, the operating system moves the mouse pointer. The mouse pointer contains a single pixel, called the hot spot, which the operating system tracks and recognizes as the position of the pointer. When the user moves the mouse or presses a mouse button, the that contains the raises the appropriate mouse event. + +You can obtain the current mouse position with the property of the when handling a mouse event or by using the property of the class. You can then use mouse location information to carry out hit-testing, and then perform an action based on the location of the mouse. Hit-testing capability is built in to several controls in Windows Forms such as the , , and controls. + +Used with the appropriate mouse event, for example, hit-testing is very useful for determining when your application should do a specific action. + +## Changing mouse input settings + +You can detect and change the way a control handles mouse input by deriving from the control and using the and methods. The method takes a bitwise combination of values to determine whether the control will have standard click, double-click behavior, or if the control will handle its own mouse processing. Also, the class includes properties that describe the capabilities of the mouse and specify how the mouse interacts with the operating system. The following table summarizes these properties. + +| Property | Description | +|------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| | Gets the dimensions, in pixels, of the area in which the user must click twice for the operating system to consider the two clicks a double-click. | +| | Gets the maximum number of milliseconds that can elapse between a first click and a second click for the mouse action to be considered a double-click. | +| | Gets the number of buttons on the mouse. | +| | Gets a value indicating whether the functions of the left and right mouse buttons have been swapped. | +| | Gets the dimensions, in pixels, of the rectangle within which the mouse pointer has to stay for the mouse hover time before a mouse hover message is generated. | +| | Gets the time, in milliseconds, that the mouse pointer has to stay in the hover rectangle before a mouse hover message is generated. | +| | Gets a value indicating whether a mouse is installed. | +| | Gets a value indicating the current mouse speed, from 1 to 20. | +| | Gets a value indicating whether a mouse with a mouse wheel is installed. | +| | Gets the amount of the delta value of the increment of a single mouse wheel rotation. | +| | Gets the number of lines to scroll when the mouse wheel is rotated. | + +## Methods that process user input messages + +Forms and controls have access to the interface and a set of overridable methods that process Windows messages at different points in the message queue. These methods all have a parameter, which encapsulates the low-level details of Windows messages. You can implement or override these methods to examine the message and then either consume the message or pass it on to the next consumer in the message queue. The following table presents the methods that process all Windows messages in Windows Forms. + +| Method | Notes | +|------------|-----------| +| | This method intercepts queued (also known as posted) Windows messages at the application level.| +| | This method intercepts Windows messages at the form and control level before they have been processed.| +| | This method processes Windows messages at the form and control level.| +| | This method performs the default processing of Windows messages at the form and control level. This provides the minimal functionality of a window.| +| | This method intercepts messages at the form and control level, after they've been processed. The style bit must be set for this method to be called.| + +## See also + +- [Using mouse events (Windows Forms .NET)](events.md) +- [Drag-and-drop mouse behavior overview (Windows Forms .NET)](drag-and-drop.md) +- [Manage mouse pointers (Windows Forms .NET)](how-to-manage-cursor-pointer.md) diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/DoubleClickButton.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/DoubleClickButton.cs new file mode 100644 index 0000000000..93759b2e9f --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/DoubleClickButton.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + // + public partial class DoubleClickButton : Button + { + public DoubleClickButton() + { + // Set the style so a double click event occurs. + SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); + } + } + // +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..a416d84fdb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.Designer.cs @@ -0,0 +1,49 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(821, 450); + this.Cursor = System.Windows.Forms.Cursors.Default; + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.cs new file mode 100644 index 0000000000..e5cc9abd7c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace project +{ + // + public partial class Form1 : Form + { + private FormBorderStyle _initialStyle; + private bool _isDoubleClicking; + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + _initialStyle = this.FormBorderStyle; + + var button1 = new DoubleClickButton(); + button1.Location = new Point(50, 50); + button1.Size = new Size(200, 23); + button1.Text = "Click or Double Click"; + button1.Click += Button1_Click; + button1.DoubleClick += Button1_DoubleClick; + + Controls.Add(button1); + } + + private void Button1_DoubleClick(object sender, EventArgs e) + { + // This flag prevents the click handler logic from running + // A double click raises the click event twice. + _isDoubleClicking = true; + FormBorderStyle = _initialStyle; + } + + private void Button1_Click(object sender, EventArgs e) + { + if (_isDoubleClicking) + _isDoubleClicking = false; + else + FormBorderStyle = FormBorderStyle.FixedToolWindow; + } + } + // +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.Designer.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.Designer.cs new file mode 100644 index 0000000000..7ae7421a89 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.Designer.cs @@ -0,0 +1,48 @@ + +namespace project +{ + partial class Form2 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // Form2 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Name = "Form2"; + this.Text = "Form2"; + this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form2_MouseDown); + this.ResumeLayout(false); + + } + + #endregion + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.cs new file mode 100644 index 0000000000..d6061dbb47 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace project +{ + public partial class Form2 : Form + { + private DateTime _lastClick; + private bool _inDoubleClick; + private Rectangle _doubleClickArea; + private TimeSpan _doubleClickMaxTime; + private Action _doubleClickAction; + private Action _singleClickAction; + private Timer _clickTimer; + + public Form2() + { + InitializeComponent(); + _doubleClickMaxTime = TimeSpan.FromMilliseconds(SystemInformation.DoubleClickTime); + + _clickTimer = new Timer(); + _clickTimer.Interval = SystemInformation.DoubleClickTime; + _clickTimer.Tick += ClickTimer_Tick; + + _singleClickAction = () => MessageBox.Show("Single clicked"); + _doubleClickAction = () => MessageBox.Show("Double clicked"); + } + + private void Form2_MouseDown(object sender, MouseEventArgs e) + { + if (_inDoubleClick) + { + _inDoubleClick = false; + + TimeSpan length = DateTime.Now - _lastClick; + + // If double click is valid, respond + if (_doubleClickArea.Contains(e.Location) && length < _doubleClickMaxTime) + { + _clickTimer.Stop(); + _doubleClickAction(); + } + + return; + } + + // Double click was invalid, restart + _clickTimer.Stop(); + _clickTimer.Start(); + _lastClick = DateTime.Now; + _inDoubleClick = true; + _doubleClickArea = new Rectangle(e.Location - (SystemInformation.DoubleClickSize / 2), + SystemInformation.DoubleClickSize); + } + + private void ClickTimer_Tick(object sender, EventArgs e) + { + // Clear double click watcher and timer + _inDoubleClick = false; + _clickTimer.Stop(); + + _singleClickAction(); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Program.cs new file mode 100644 index 0000000000..805b410d9e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form2()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/project.csproj new file mode 100644 index 0000000000..07703cca4c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/csharp/project.csproj @@ -0,0 +1,13 @@ + + + + WinExe + net5.0-windows + true + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/DoubleClickButton.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/DoubleClickButton.vb new file mode 100644 index 0000000000..6c29bb61d7 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/DoubleClickButton.vb @@ -0,0 +1,11 @@ +Imports System.Windows.Forms + +' +Public Class DoubleClickButton : Inherits Button + + Public Sub New() + SetStyle(ControlStyles.StandardClick Or ControlStyles.StandardDoubleClick, True) + End Sub + +End Class +' diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.Designer.vb new file mode 100644 index 0000000000..e1647fb0f5 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.Designer.vb @@ -0,0 +1,37 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.SuspendLayout() + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + + End Sub +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.vb new file mode 100644 index 0000000000..ee47aaa387 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form1.vb @@ -0,0 +1,45 @@ +Imports System.Windows.Forms +Imports System.Drawing + +' +Partial Public Class Form1 + + Private _initialStyle As FormBorderStyle + Private _isDoubleClicking As Boolean + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load + Dim button1 As New DoubleClickButton + + _initialStyle = FormBorderStyle + + button1.Location = New Point(50, 50) + button1.Size = New Size(200, 23) + button1.Text = "Click or Double Click" + + AddHandler button1.Click, AddressOf Button1_Click + AddHandler button1.DoubleClick, AddressOf Button1_DoubleClick + + Controls.Add(button1) + + End Sub + + Private Sub Button1_DoubleClick(sender As Object, e As EventArgs) + ' This flag prevents the click handler logic from running + ' A double click raises the click event twice. + _isDoubleClicking = True + FormBorderStyle = _initialStyle + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) + If _isDoubleClicking Then + _isDoubleClicking = False + Else + FormBorderStyle = FormBorderStyle.FixedToolWindow + End If + End Sub +End Class +' diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.Designer.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.Designer.vb new file mode 100644 index 0000000000..a5ce221b5a --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.Designer.vb @@ -0,0 +1,37 @@ + _ +Partial Class Form2 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.SuspendLayout() + ' + 'Form2 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Name = "Form2" + Me.Text = "Form2 vb" + Me.ResumeLayout(False) + + End Sub +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.vb new file mode 100644 index 0000000000..3a39e8678a --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Form2.vb @@ -0,0 +1,61 @@ +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form2 + Private _lastClick As Date + Private _inDoubleClick As Boolean + Private _doubleClickArea As Rectangle + Private _doubleClickMaxTime As TimeSpan + Private _singleClickAction As Action + Private _doubleClickAction As Action + Private WithEvents _clickTimer As Timer + + Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load + _doubleClickMaxTime = TimeSpan.FromMilliseconds(SystemInformation.DoubleClickTime) + + _clickTimer = New Timer() + _clickTimer.Interval = SystemInformation.DoubleClickTime + + _singleClickAction = Sub() + MessageBox.Show("Single click") + End Sub + + _doubleClickAction = Sub() + MessageBox.Show("Double click") + End Sub + End Sub + + Private Sub Form2_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown + If _inDoubleClick Then + + _inDoubleClick = False + + Dim length As TimeSpan = Date.Now - _lastClick + + ' If double click is valid, respond + If _doubleClickArea.Contains(e.Location) And length < _doubleClickMaxTime Then + _clickTimer.Stop() + Call _doubleClickAction() + End If + + Return + End If + + ' Double click was invalid, restart + _clickTimer.Stop() + _clickTimer.Start() + _lastClick = Date.Now + _inDoubleClick = True + _doubleClickArea = New Rectangle(e.Location - (SystemInformation.DoubleClickSize / 2), + SystemInformation.DoubleClickSize) + End Sub + + Private Sub SingleClickTimer_Tick(sender As Object, e As EventArgs) Handles _clickTimer.Tick + ' Clear double click watcher and timer + _inDoubleClick = False + _clickTimer.Stop() + + Call _singleClickAction() + End Sub + +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Program.vb new file mode 100644 index 0000000000..6433d1e7db --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form2()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/projectvb.vbproj new file mode 100644 index 0000000000..915530d2eb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-distinguish-between-clicks-and-double-clicks/vb/projectvb.vbproj @@ -0,0 +1,14 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..7812f51774 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.Designer.cs @@ -0,0 +1,78 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(232, 110); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 28); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + this.button1.MouseEnter += new System.EventHandler(this.button1_MouseEnter); + this.button1.MouseLeave += new System.EventHandler(this.button1_MouseLeave); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(398, 115); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(75, 23); + this.button2.TabIndex = 1; + this.button2.Text = "button2"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(821, 455); + this.Controls.Add(this.button2); + this.Controls.Add(this.button1); + this.Cursor = System.Windows.Forms.Cursors.Default; + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button2; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.cs new file mode 100644 index 0000000000..b4b98a5619 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace project +{ + public partial class Form1 : Form + { + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + // + button2.Cursor = System.Windows.Forms.Cursors.Hand; + // + } + + // + private void button1_Click(object sender, EventArgs e) => + Cursor.Position = PointToScreen(button2.Location); + + private void button2_Click(object sender, EventArgs e) => + Cursor.Position = PointToScreen(button1.Location); + // + + // + private void button1_MouseEnter(object sender, EventArgs e) => + Cursor.Hide(); + + private void button1_MouseLeave(object sender, EventArgs e) => + Cursor.Show(); + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Program.cs new file mode 100644 index 0000000000..07516585b7 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/project.csproj new file mode 100644 index 0000000000..07703cca4c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/csharp/project.csproj @@ -0,0 +1,13 @@ + + + + WinExe + net5.0-windows + true + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.Designer.vb new file mode 100644 index 0000000000..af7152146b --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.Designer.vb @@ -0,0 +1,62 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.Button2 = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(228, 103) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Button2 + ' + Me.Button2.Location = New System.Drawing.Point(358, 149) + Me.Button2.Name = "Button2" + Me.Button2.Size = New System.Drawing.Size(75, 23) + Me.Button2.TabIndex = 1 + Me.Button2.Text = "Button2" + Me.Button2.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Button2) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + + End Sub + + Friend WithEvents Button1 As Windows.Forms.Button + Friend WithEvents Button2 As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.vb new file mode 100644 index 0000000000..b733890504 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Form1.vb @@ -0,0 +1,36 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load + ' + Button2.Cursor = System.Windows.Forms.Cursors.Hand + ' + End Sub + + ' + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + PointToScreen(Button2.Location) + End Sub + + Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click + PointToScreen(Button1.Location) + End Sub + ' + + ' + Private Sub Button1_MouseEnter(sender As Object, e As EventArgs) Handles Button1.MouseEnter + Cursor.Hide() + End Sub + + Private Sub Button1_MouseLeave(sender As Object, e As EventArgs) Handles Button1.MouseLeave + Cursor.Show() + End Sub + ' + +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Program.vb new file mode 100644 index 0000000000..3551285240 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/projectvb.vbproj new file mode 100644 index 0000000000..915530d2eb --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-manage-cursor-pointer/vb/projectvb.vbproj @@ -0,0 +1,14 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..f5f4f5a25a --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.Designer.cs @@ -0,0 +1,77 @@ +namespace project +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.checkBox1 = new System.Windows.Forms.CheckBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // checkBox1 + // + this.checkBox1.AutoSize = true; + this.checkBox1.Location = new System.Drawing.Point(93, 15); + this.checkBox1.Name = "checkBox1"; + this.checkBox1.Size = new System.Drawing.Size(83, 19); + this.checkBox1.TabIndex = 5; + this.checkBox1.Text = "checkBox1"; + this.checkBox1.UseVisualStyleBackColor = true; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(821, 450); + this.Controls.Add(this.checkBox1); + this.Controls.Add(this.button1); + this.Cursor = System.Windows.Forms.Cursors.Default; + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.CheckBox checkBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.cs new file mode 100644 index 0000000000..33f627d409 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace project +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // + private void button1_Click(object sender, EventArgs e) + { + InvokeOnClick(checkBox1, EventArgs.Empty); + } + // + + private void SimulateButtonClick() + { + // + button1.PerformClick(); + // + } + + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.Designer.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.Designer.cs new file mode 100644 index 0000000000..620fe33107 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.Designer.cs @@ -0,0 +1,76 @@ +namespace project +{ + partial class Form2 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.checkBox1 = new System.Windows.Forms.CheckBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // checkBox1 + // + this.checkBox1.AutoSize = true; + this.checkBox1.Location = new System.Drawing.Point(93, 15); + this.checkBox1.Name = "checkBox1"; + this.checkBox1.Size = new System.Drawing.Size(83, 19); + this.checkBox1.TabIndex = 1; + this.checkBox1.Text = "checkBox1"; + this.checkBox1.UseVisualStyleBackColor = true; + // + // Form2 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.checkBox1); + this.Controls.Add(this.button1); + this.Name = "Form2"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.CheckBox checkBox1; + } +} + diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.cs new file mode 100644 index 0000000000..aeb5cae974 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + public partial class Form2 : Form + { + + public Form2() + { + InitializeComponent(); + } + + // + [DllImport("user32.dll", EntryPoint = "SetCursorPos")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetCursorPos(int x, int y); + + private void button1_Click(object sender, EventArgs e) + { + Point position = PointToScreen(checkBox1.Location) + new Size(checkBox1.Width / 2, checkBox1.Height / 2); + SetCursorPos(position.X, position.Y); + } + // + + private void Form1_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Program.cs new file mode 100644 index 0000000000..805b410d9e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace project +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form2()); + } + } +} diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/project.csproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/project.csproj new file mode 100644 index 0000000000..9c3d193f6c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/csharp/project.csproj @@ -0,0 +1,14 @@ + + + + WinExe + net5.0-windows + true + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.Designer.vb new file mode 100644 index 0000000000..f2bf40ac09 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.Designer.vb @@ -0,0 +1,76 @@ + _ +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.CheckBox1 = New System.Windows.Forms.CheckBox() + Me.Button2 = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'CheckBox1 + ' + Me.CheckBox1.AutoSize = True + Me.CheckBox1.Location = New System.Drawing.Point(93, 15) + Me.CheckBox1.Name = "CheckBox1" + Me.CheckBox1.Size = New System.Drawing.Size(85, 19) + Me.CheckBox1.TabIndex = 1 + Me.CheckBox1.Text = "CheckBox1" + Me.CheckBox1.UseVisualStyleBackColor = True + ' + 'Button2 + ' + Me.Button2.Location = New System.Drawing.Point(12, 40) + Me.Button2.Name = "Button2" + Me.Button2.Size = New System.Drawing.Size(75, 23) + Me.Button2.TabIndex = 2 + Me.Button2.Text = "Button2" + Me.Button2.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Button2) + Me.Controls.Add(Me.CheckBox1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = " form1 vb" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend WithEvents Button1 As Windows.Forms.Button + Friend WithEvents CheckBox1 As Windows.Forms.CheckBox + Friend WithEvents Button2 As Windows.Forms.Button +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.vb new file mode 100644 index 0000000000..75dd32c569 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form1.vb @@ -0,0 +1,27 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form1 + + Public Sub New() + InitializeComponent() + + End Sub + + ' + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + InvokeOnClick(CheckBox1, EventArgs.Empty) + End Sub + ' + + Private Sub SimulateButtonClick() + ' + Button1.PerformClick() + ' + End Sub + + Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click + + End Sub + +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.Designer.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.Designer.vb new file mode 100644 index 0000000000..565a042b52 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.Designer.vb @@ -0,0 +1,64 @@ + +Partial Class Form2 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.CheckBox1 = New System.Windows.Forms.CheckBox() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + Me.Button1.UseVisualStyleBackColor = True + ' + 'CheckBox1 + ' + Me.CheckBox1.AutoSize = True + Me.CheckBox1.Location = New System.Drawing.Point(93, 14) + Me.CheckBox1.Name = "CheckBox1" + Me.CheckBox1.Size = New System.Drawing.Size(85, 19) + Me.CheckBox1.TabIndex = 1 + Me.CheckBox1.Text = "CheckBox1" + Me.CheckBox1.UseVisualStyleBackColor = True + ' + 'Form2 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.CheckBox1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form2" + Me.Text = "Form1 vb" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend WithEvents Button1 As Windows.Forms.Button + Friend WithEvents CheckBox1 As Windows.Forms.CheckBox +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.resx b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.resx new file mode 100644 index 0000000000..f298a7be80 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.vb new file mode 100644 index 0000000000..2aa5508e34 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Form2.vb @@ -0,0 +1,19 @@ +Imports System.Windows.Forms +Imports System.Drawing + +Partial Public Class Form2 + + Public Sub New() + InitializeComponent() + End Sub + + ' + + Public Shared Function SetCursorPos(x As Integer, y As Integer) As Boolean : End Function + + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + Dim position As Point = PointToScreen(CheckBox1.Location) + New Size(CheckBox1.Width / 2, CheckBox1.Height / 2) + SetCursorPos(position.X, position.Y) + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Program.vb b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Program.vb new file mode 100644 index 0000000000..6433d1e7db --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/Program.vb @@ -0,0 +1,15 @@ +Imports System +Imports System.Collections.Generic +Imports System.Linq +Imports System.Threading.Tasks +Imports System.Windows.Forms + +Module Program + Sub Main(args As String()) + Application.SetHighDpiMode(HighDpiMode.SystemAware) + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form2()) + End Sub + +End Module diff --git a/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/projectvb.vbproj b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/projectvb.vbproj new file mode 100644 index 0000000000..f631d30f94 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/input-mouse/snippets/how-to-simulate-events/vb/projectvb.vbproj @@ -0,0 +1,15 @@ + + + + WinExe + net5.0-windows + true + Sub Main + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/media/visual-studio-ellipsis-button.png b/dotnet-desktop-guide/net/winforms/media/visual-studio-ellipsis-button.png new file mode 100644 index 0000000000..6c613e4230 Binary files /dev/null and b/dotnet-desktop-guide/net/winforms/media/visual-studio-ellipsis-button.png differ diff --git a/dotnet-desktop-guide/net/winforms/overview/index.md b/dotnet-desktop-guide/net/winforms/overview/index.md new file mode 100644 index 0000000000..0362e6ab40 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/overview/index.md @@ -0,0 +1,128 @@ +--- +title: What is Windows Forms +description: This article gives an overview of Windows Forms with .NET Core and .NET 5. +ms.date: 10/26/2020 +ms.topic: overview +#Customer intent: As a developer, I want to understand the components of Windows Forms so that I can understand the overall picture of Windows Forms. +--- + +# Desktop Guide (Windows Forms .NET) + +Welcome to the Desktop Guide for Windows Forms, a UI framework that creates rich desktop client apps for Windows. The Windows Forms development platform supports a broad set of app development features, including controls, graphics, data binding, and user input. Windows Forms features a drag-and-drop visual designer in Visual Studio to easily create Windows Forms apps. + +[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] + +There are two implementations of Windows Forms: + +01. The open-source implementation hosted on [GitHub](https://github.com/dotnet/winforms). + + This version runs on .NET 5 and .NET Core 3.1. The Windows Forms Visual Designer requires, at a minimum, [Visual Studio 2019 version 16.8 Preview](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019+desktopguide+winforms). + +01. The .NET Framework 4 implementation that's supported by Visual Studio 2019 and Visual Studio 2017. + + .NET Framework 4 is a Windows-only version of .NET and is considered a Windows Operating System component. This version of Windows Forms is distributed with .NET Framework. + +This Desktop Guide is written for Windows Forms on .NET 5. For more information about the .NET Framework version of Windows Forms, see [Windows Forms for .NET Framework](../../../framework/winforms/index.yml?view=netframeworkdesktop-4.8&preserve-view=true). + +## Introduction + +Windows Forms is a UI framework for building Windows desktop apps. It provides one of the most productive ways to create desktop apps based on the visual designer provided in Visual Studio. Functionality such as drag-and-drop placement of visual controls makes it easy to build desktop apps. + +With Windows Forms, you develop graphically rich apps that are easy to deploy, update, and work while offline or while connected to the internet. Windows Forms apps can access the local hardware and file system of the computer where the app is running. + +To learn how to create a Windows Forms app, see [Tutorial: Create a new WinForms app (Windows Forms .NET)](../get-started/create-app-visual-studio.md). + +## Build rich, interactive user interfaces + +Windows Forms is a UI technology for .NET, a set of managed libraries that simplify common app tasks such as reading and writing to the file system. When you use a development environment like Visual Studio, you can create Windows Forms smart-client apps that display information, request input from users, and communicate with remote computers over a network. + +In Windows Forms, a *form* is a visual surface on which you display information to the user. You ordinarily build Windows Forms apps by adding controls to forms and developing responses to user actions, such as mouse clicks or key presses. A *control* is a discrete UI element that displays data or accepts data input. + +When a user does something to your form or one of its controls, the action generates an event. Your app reacts to these events with code, and processes the events when they occur. + +Windows Forms contains a variety of controls that you can add to forms: controls that display text boxes, buttons, drop-down boxes, radio buttons, and even webpages. If an existing control doesn't meet your needs, Windows Forms also supports creating your own custom controls using the class. + +Windows Forms has rich UI controls that emulate features in high-end apps like Microsoft Office. When you use the and controls, you can create toolbars and menus that contain text and images, display submenus, and host other controls such as text boxes and combo boxes. + +With the drag-and-drop **Windows Forms Designer** in Visual Studio, you can easily create Windows Forms apps. Just select the controls with your cursor and place them where you want on the form. The designer provides tools such as gridlines and snap lines to take the hassle out of aligning controls. You can use the , , and controls to create advanced form layouts in less time. + +Finally, if you must create your own custom UI elements, the namespace contains a large selection of classes to render lines, circles, and other shapes directly on a form. + +### Create forms and controls + +For step-by-step information about how to use these features, see the following Help topics. + +- [How to add a form to a project](../forms/how-to-add.md) +- [How to add Controls to to a form](../controls/how-to-add-to-a-form.md) + + + +## Display and manipulate data + +Many apps must display data from a database, XML or JSON file, web service, or other data source. Windows Forms provides a flexible control that is named the control for displaying such tabular data in a traditional row and column format, so that every piece of data occupies its own cell. When you use , you can customize the appearance of individual cells, lock arbitrary rows and columns in place, and display complex controls inside cells, among other features. + +Connecting to data sources over a network is a simple task with Windows Forms. The component represents a connection to a data source, and exposes methods for binding data to controls, navigating to the previous and next records, editing records, and saving changes back to the original source. The control provides a simple interface over the component for users to navigate between records. + +You can create data-bound controls easily by using the Data Sources window in Visual Studio. The window displays data sources such as databases, web services, and objects in your project. You can create data-bound controls by dragging items from this window onto forms in your project. You can also data-bind existing controls to data by dragging objects from the Data Sources window onto existing controls. + +Another type of data binding you can manage in Windows Forms is *settings*. Most apps must retain some information about their run-time state, such as the last-known size of forms, and retain user preference data, such as default locations for saved files. The Application Settings feature addresses these requirements by providing an easy way to store both types of settings on the client computer. After you define these settings by using either Visual Studio or a code editor, the settings are persisted as XML and automatically read back into memory at run time. + + + +## Deploy apps to client computers + +After you have written your app, you must send the app to your users so that they can install and run it on their own client computers. When you use the ClickOnce technology, you can deploy your apps from within Visual Studio by using just a few clicks, and provide your users with a URL pointing to your app on the web. ClickOnce manages all the elements and dependencies in your app, and ensures that the app is correctly installed on the client computer. + +ClickOnce apps can be configured to run only when the user is connected to the network, or to run both online and offline. When you specify that an app should support offline operation, ClickOnce adds a link to your app in the user's **Start** menu. The user can then open the app without using the URL. + +When you update your app, you publish a new deployment manifest and a new copy of your app to your web server. ClickOnce will detect that there is an update available and upgrade the user's installation. No custom programming is required to update old apps. + + + + + +## See also + +- [Tutorial: Create a new WinForms app (Windows Forms .NET)](../get-started/create-app-visual-studio.md) +- [How to add a form to a project (Windows Forms .NET)](../forms/how-to-add.md) +- [Add a control (Windows Forms .NET)](../controls/how-to-add-to-a-form.md) diff --git a/dotnet-desktop-guide/net/winforms/toc.yml b/dotnet-desktop-guide/net/winforms/toc.yml index 634940a292..ea34719c6b 100644 --- a/dotnet-desktop-guide/net/winforms/toc.yml +++ b/dotnet-desktop-guide/net/winforms/toc.yml @@ -1,3 +1,81 @@ items: -- name: Windows Forms - href: index.md +- name: Windows Forms for .NET + href: index.yml +- name: Get started + items: + - name: Overview + href: overview/index.md + - name: Create an app + href: get-started/create-app-visual-studio.md +- name: Forms + items: + - name: Event handlers + href: forms/events.md + - name: Automatic scaling + href: forms/autoscale.md + - name: Common tasks + items: + - name: Add a form + href: forms/how-to-add.md + - name: Resize a form + href: forms/how-to-position-and-resize.md + - name: Position a form + href: forms/how-to-position-and-resize.md#position-with-the-designer +- name: Controls + items: + - name: Overview + href: controls/overview.md + - name: Layout options + href: controls/layout.md + - name: Labels + href: controls/labels.md + - name: Custom controls + href: controls/custom.md + - name: Custom painting and drawing + href: controls/custom-painting-drawing.md + - name: Apply accessibility information + href: controls/provide-accessibility-information.md + - name: Common tasks + items: + - name: Add a control to a form + href: controls/how-to-add-to-a-form.md + - name: Create access key shortcuts + href: controls/how-to-create-access-keys.md + - name: Set the text displayed by a control + href: controls/how-to-set-the-display-text.md + - name: Set the image displayed by a control + href: controls/how-to-add-a-picture-to-a-control.md +- name: User input - keyboard + items: + - name: Overview + href: input-keyboard/overview.md + - name: Use keyboard events + href: input-keyboard/events.md + - name: Validate input + href: input-keyboard/validation.md + - name: Common tasks + items: + - name: Change the pressed key + href: input-keyboard/how-to-change-key-press.md + - name: Determine which modifier key is pressed + href: input-keyboard/how-to-check-modifier-key.md + - name: Handle input at the form level + href: input-keyboard/how-to-handle-forms.md + - name: Simulate keyboard events + href: input-keyboard/how-to-simulate-events.md +- name: User input - mouse + items: + - name: Overview + href: input-mouse/overview.md + - name: Use mouse events + href: input-mouse/events.md + - name: Drag-and-drop functionality + href: input-mouse/drag-and-drop.md + - name: Common tasks + items: + - name: Distinguish between clicks and double-clicks + href: input-mouse/how-to-distinguish-between-clicks-and-double-clicks.md + - name: Control and modify the mouse pointer + href: input-mouse/how-to-manage-cursor-pointer.md + - name: Simulate mouse events + href: input-mouse/how-to-simulate-events.md